都在推荐用Requests库,而不是Urllib,但是读取网页的时候中文会出现乱码。
分析: r = requests.get(“http://www.baidu.com“)
r.text返回的是Unicode型的数据。 使用r.content返回的是bytes型的数据。 也就是说,如果你想取文本,可以通过r.text。 如果想取图片文件,则可以通过r.content。
比如在下面这种就会出现乱码(中文乱码):
import requests
url="http://m.tlyy.cc/dsj/dsj1/index.html"
r=requests.get(url)
print(r.text)
解决方法:参照https://www.cnblogs.com/sheng-247/p/7686014.html,修改之后就没有问题了。
import requests
import re
req = requests.get("http://m.tlyy.cc/dsj/dsj1/index.html")
if req.encoding == 'ISO-8859-1':
encodings = requests.utils.get_encodings_from_content(req.text)
if encodings:
encoding = encodings[0]
else:
encoding = req.apparent_encoding
# encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace')
global encode_content
encode_content = req.content.decode(encoding, 'replace') #如果设置为replace,则会用?取代非法字符;
print(encode_content)
pattern = re.compile('<a.*?title="(.*?) class="apic"><img src="(.*?)".*?</a>',re.S)
# <a href="/dsj/dsj1/hongshatuji/" title="红鲨突击" class="apic">
# <img src="http://pic.xintexin.cn/uploadimg/2019-11/201911510271471042.jpg"
# alt="红鲨突击" /></a><p><a href="/dsj/dsj1/hongshatuji/">红鲨突击</a>
items = re.findall(pattern,encode_content)
for item in items:
print(item[0])
print(item[1])