m0_52092477
2021-05-30 23:14
采纳率: 100%
浏览 57

怎么解决python爬虫写入txt文件时出现的中文乱码问题

import requests
import re
from lxml import html

class MyCrawler:
    def __init__(self, filename):
        self.filename = filename
        self.headers =  {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        }
    
    def download(self, url):
        r = requests.get(url, headers=self.headers)
        return r.text
    
    def extract(self, content, pattern):
        result = re.findall(pattern, content)
        return result
    
    def save(self, info):
        with open(self.filename, 'w', encoding='utf-8') as f:
            for item in info:
                f.write('|||'.join(item) + '\n')
    
    def crawl(self, url, pattern, headers=None):
        if headers:
            self.headers.update(headers)
        content = self.download(url)
        info = self.extract(content, pattern)
        self.save(info)
        
b_crawler = MyCrawler('douban.txt')
b_crawler.crawl(
    'http://lyjs.eastday.com/',
    'n\d+\/index.html"\starget="_blank">(.*?)<\/a></span></div><div\sclass="level">(.*?)<\/div>'
)
with open('douban.txt','r',encoding='utf-8') as f:
    lines=f.read()
    for line in lines.split('\n'):
        print(line)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • CSDN专家-HGJ 2021-05-30 23:34
    已采纳

    在download函数代码中添加一行:r.encoding=r.apparent_encoding即可。

    def download(self, url):
        r = requests.get(url, headers=self.headers)
        r.encoding=r.apparent_encoding
        return r.text
           

    如有帮助,请点采纳,谢谢。

    点赞 1 打赏 评论
  • 有问必答小助手 2021-05-31 11:15

    您的问题已经有小伙伴解答了,请点击【采纳】按钮,采纳帮您提供解决思路的答案,给回答的人一些鼓励哦~~

    ps:开通问答VIP,享受5次/月 有问必答服务,了解详情↓↓↓

    【电脑端】戳>>>  https://vip.csdn.net/askvip?utm_source=1146287632
    【APP 】  戳>>>  https://mall.csdn.net/item/52471?utm_source=1146287632

    点赞 打赏 评论