python爬虫中通用的两种乱码解决方式(自用)

问题:在python爬虫爬取的时候,我们有时会遇到诸如以下的乱码:

�װŮ�� ��Ů ˮ СϪ Ψ��
ÃÀÅ® µçÄÔ×À ¼üÅÌ »ú·¿ ¿É°® С½ã½ã4k±ÚÖ½

解决方法一:用utf-8来转码,具体在请求过程中如下

	page_text = requests.get(url=url,headers=headers)
    page_text.encoding = 'utf-8'
	# 开始正常使用
    tree = etree.HTML(page_text.text)

解决方法二:用通用的中文乱码处理方式:

		#通用中文乱码解决方案
        img_name = img_name.encode('iso-8859-1').decode('gbk')

下面给出具体的运用例子:(仅供学习交流)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os.path
import requests
from lxml import etree

# from bs4 import BeautifulSoup
#需求:爬取三国演义小说所有的章节标题和章节内容http://www.shicimingju.com/book/sanguoyanyi.html
if __name__ == "__main__":
    #对首页的页面数据进行爬取
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
    }
    url = 'https://pic.netbian.com/4kdongman/'
    page_text = requests.get(url=url,headers=headers).text
    # page_text.encoding = 'utf-8'

    tree = etree.HTML(page_text)
    li_list = tree.xpath('//*[@id="main"]/div[3]/ul/li')

    if not os.path.exists('./picLibs'):
        os.mkdir('./picLibs')

    for li in li_list:
        img_src = 'https://pic.netbian.com/' + li.xpath('./a/img/@src')[0]
        img_name = li.xpath('./a/img/@alt')[0] + '.jpg'
        #通用中文乱码解决方案
        img_name = img_name.encode('iso-8859-1').decode('gbk')
        img_data = requests.get(url=img_src,headers=headers).content
        img_path = 'picLibs/' + img_name
        with open(img_path,'wb') as fp:
            fp.write(img_data)
            print(img_name,"下载成功!!")




你可能感兴趣的:(爬虫,python,爬虫,开发语言)