会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 134510个问题

老师,我在使用多线程爬取文件的时候,会出现文件写入不全,然后我在写入文件的的时候加入锁,但是发现还写入不全,您帮我看一下!

from threading import Thread,Lock
import requests
from lxml import etree
from fake_useragent import UserAgent
from queue import Queue
class Spider(Thread):
    def __init__(self,url_queue,lock):
        Thread.__init__(self)
        self.url_queue = url_queue
        self.lock = lock

    def run(self):
        while not self.url_queue.empty():
            url = self.url_queue.get()
            print(url)
            headers = {'User-Agent':UserAgent().chrome}
            resp = requests.get(url,headers=headers)
            e = etree.HTML(resp.text)
            contents = [div.xpath('string(.)').strip() for div in e.xpath('//div[@class="content"]')]
            #加入锁
            self.lock.acquire()
            with open('qiushi.text', 'a', encoding='utf-8')as f:
                for content in contents:
                    f.write(content+'\n')
            self.lock.release()
if __name__ == '__main__':
    base_url = 'https://www.qiushibaike.com/text/page/{}/'
    lock = Lock()
    url_queue = Queue()
    for num in range(1,14):
        url_queue.put(base_url.format(num))
    for i in range(6):
        spider = Spider(url_queue,lock)
        spider.start()


Python全系列/第十六阶段:Python 爬虫开发/爬虫反反爬- 32楼
Python全系列/第十六阶段:Python 爬虫开发/scrapy框架使用 33楼

'''
出现中文乱码的问题,编码形式改为‘utf-8’;
出现\u这种问题,照着dumps()方法中的ensure_ascii=False进行修改。
'''
import json

str_1 = '{"name":"战狼3"}'
print(type(str_1))        # 返回<class 'str'>
print(str_1)        #返回{"name":"战狼3"}


print('----str_1 to obj_1----')
# 把Json格式字符串解码转换成Python对象
obj_1 = json.loads(str_1)
print(obj_1)      # 返回{'name': '战狼3'}
print(type(obj_1))        # 返回<class 'dict'>  


print('----obj_1 to str_2----')
# 实现python类型转化为json字符串,返回⼀个str_2对象
str_2 = json.dumps(obj_1)     # str_2返回Unicode编码
# str_2 = json.dumps(obj_1,ensure_ascii=False)      # 将ensure_ascii=False,可使Unicode编码转为原生编码
print(str_2)        # 未将ensure_ascii=False,则返回{"name": "\u6218\u72fc3"}
# print(str_2)        # 将ensure_ascii=False,则返回{"name": "战狼3"}
print(type(str_2))      # 返回<class 'str'>


print('----obj_1 to file----')
# obj_1 to file,将Python内置类型序列化为json对象后写⼊⽂件
json.dump(obj_1,open('movie.txt','w',encoding='utf-8',ensure_ascii=False))       # 写文件movie.txt


print('----file to obj_2----')
# file to obj_2,读取⽂件中json形式的字符串元素 转化成python类型
obj_2 = json.load(open('movie.txt',encoding='utf-8'))
print(obj_2)        # encoding = 'utf-8',返回{'name': '战狼3'}
print(type(obj_2))      # 返回<class 'dict'>

图片.png

图片.png

图片.png

老师,你好,我测试了一下这个错误点一个是在开头注释的\u,然后还有写movie文件中的ensure_ascii=False,好像是无效的关键字参数,那我写在注释里的\u为什么是错的,然后还有‘写文件’中出现这样的情况怎么把它改成中文。对于这个编码之间的转换不太了解,试着掌握很多次了,可印象还是不深刻。



Python全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 34楼
Python全系列/第十六阶段:Python 爬虫开发/移动端爬虫 35楼
Python全系列/第十六阶段:Python 爬虫开发/移动端爬虫 36楼
Python全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 37楼
Python全系列/第十六阶段:Python 爬虫开发/scrapy框架使用(旧) 38楼
Python全系列/第十六阶段:Python 爬虫开发/scrapy框架使用(旧) 39楼

image.png


Python全系列/第十六阶段:Python 爬虫开发/移动端爬虫 40楼
Python全系列/第十六阶段:Python 爬虫开发/移动端爬虫 42楼
Python全系列/第十六阶段:Python 爬虫开发/爬虫反反爬- 43楼

image.png

Python全系列/第十六阶段:Python 爬虫开发/爬虫基础 45楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2026百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637