抓网页,数据无法解码,看着不像编码给错

2017-12-17 22:56:00 +08:00
 hukangha

初学... 代码是这样:

from html.parser import HTMLParser
import urllib.request
import chardet

pars = HTMLParser()
home_url = "https://wallstreetcn.com/"
response = urllib.request.urlopen(home_url)
content = response.read()
encoding = chardet.detect(content)
pars.feed(content.decode(encoding["encoding"],errors="ignore"))

chrome 看网页 metadata 里面 charset 用的 utf-8,我这里无论直接用'utf-8' 还是检测编码,均无法正确解码,有点 response 根本就没给出正确数据的感觉。请教一下

2663 次点击
所在节点    Python
7 条回复
n329291362
2017-12-17 23:46:54 +08:00
1f8b 开头。。。。gzip 压缩啊 最简单的
import gzip
gzip.decompress(content)
swordspoet
2017-12-18 00:48:49 +08:00
换一个 HTML 解析器,html.parser 的容错率不高,试试看 lxml
swordspoet
2017-12-18 00:51:39 +08:00
from bs4 import BeautifulSoup

standard_html = BeautifulSoup(content, 'lxml')

试试看这个~
free9fw
2017-12-18 09:29:26 +08:00
Accept-Encoding:gzip, deflate, br
hukangha
2017-12-18 22:06:47 +08:00
@n329291362
果然... 可是如果是其他的压缩什么的怎么办... 只能这样靠丰富的经验么...
n329291362
2017-12-19 01:50:08 +08:00
@hukangha
也可以控制头 Accept-Encoding 让服务端返回没压缩过的数据
网页最多也就是 gzip 压缩 在复杂也复杂不到哪
F1024
2017-12-27 15:59:04 +08:00
import os
import requests

html = requests.get('https://wallstreetcn.com').content.decode('utf-8')
print(html)

os.system("pause")

是这个吗

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/415536

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX