Always keep a beginner's mind,|

Dancing-Pierre

园龄:1年9个月粉丝:3关注:0

Python 爬虫中文返回乱码

Python 爬虫中文返回乱码

1、情景复现

今天闲的无聊,就复习一下爬虫,先拿学校官网做实验,爬取学校官网新闻标题、时间以及链接,可是返回的中文一直是如下的乱码:

在这里插入图片描述

2、尝试解决

我们先查看要爬取的网站的编码方式,在要爬取的网站用鼠标 右击–>检查–>点击Console 输入 document.charse 即可显示出网页的编码格式,如图:

在这里插入图片描述

一开始我们的代码是:

import requests
from lxml import etree
html = requests.get('https://www.cczu.edu.cn/')
tree = etree.HTML(html.text)
a = tree.xpath("//ul[@class='clearfix']/li")
total = []
for i in a:
title = ''.join(i.xpath('.//h2//text()'))
time = ''.join(i.xpath('.//h3//text()'))
link = ''.join(i.xpath('./h2/a/@href'))
print(title, time, link)

那咱来根据其网页的编码格式,把 request 返回的乱码转换一下:

import requests
from lxml import etree
html = requests.get('https://www.cczu.edu.cn/')
# 新增编码格式
html.encoding = "utf-8"
tree = etree.HTML(html.text)
a = tree.xpath("//ul[@class='clearfix']/li")
total = []
for i in a:
title = ''.join(i.xpath('.//h2//text()'))
time = ''.join(i.xpath('.//h3//text()'))
link = ''.join(i.xpath('./h2/a/@href'))
print(title, time, link)

完美解决!

在这里插入图片描述

本文作者:Dancing-Pierre

本文链接:https://www.cnblogs.com/wyc-1009/p/17548007.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Dancing-Pierre  阅读(10)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起