处理爬虫遇到的乱码问题

import requests

from lxml import etree

 

url = 'http://pic.netbian.com/4kqiche/'

headers = {

    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'

}

response = requests.get(url=url,headers=headers)

#手动设置响应数据的编码

# response.encoding = 'utf-8'

page_text = response.text

 

tree = etree.HTML(page_text)

li_list = tree.xpath('//div[@class="slist"]/ul/li')

for li in li_list:

    img_src = li.xpath('./a/img/@src')[0]

    img_name = li.xpath('./a/b/text()')[0]

    #通用性

    img_name = img_name.encode('iso-8859-1').decode('gbk')

    print(img_src,img_name) 

 

在我们爬取网页的时候,可能会遇到乱码的问题,解决这种的乱码的问题有一种通用的方法

 

posted @ 2019-05-27 22:23  Python张梦书  阅读(175)  评论(0编辑  收藏  举报