当前位置:   article > 正文

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

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

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

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

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

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

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

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

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

#!/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,"下载成功!!")




  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/573309
推荐阅读
相关标签
  

闽ICP备14008679号