Python请求:页面的html在文本格式中不可见

时间:2017-11-18 16:38:36

标签: python html python-requests

我正在尝试访问某个网页,它的html看起来像是:

?2?pɢ???=???I????܉??s????   [??AX#?`s??5???2`?| ,q?ɲ?=h?}VTŬ~?Y?}u3cx?pȢ?K_Ol&ɡ??'N??Y??n5?890??G???&$?%J#?ܩ?ѡ
1?y???
$]    &'ι?\?~T?=??@N?C?$??K? ??iu"T?M
  ?6>?&5?:??sJ???xi???V??N??????3R7u??ǹ??7qs??<*????????@3?
EWu}??'F??Z??߶O?????Fc۰?S???h??/????h???[kS(                        f?\˹?@e???7_~~??*'?Jq??i?͛?J?W?T?Y]S??ӫ?~??k՘H??
w?L??ws??M?h?V?؊<[ ?
??A?G?w?

那是什么?它是一些编码/解码的东西?如何查看html?

代码在这里:

import requests
from bs4 import BeautifulSoup
import json



headers_initial = {
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'en-US,en;q=0.9',
        'cache-control': 'no-cache',
        'upgrade-insecure-requests': '1',
    }    
r = requests.get('https://www.example.com/', headers=headers_initial)
        if r.status_code == 200:
            html = r.text.strip()
            print(html)

1 个答案:

答案 0 :(得分:2)

问题来自你的标题。只需删除accept-encoding,它就可以正常工作。

编辑accept-encoding指定我们是否可以处理压缩数据。 requests没有,所以如果您需要指定标题,请使用identity属性,这意味着&#34;只需将页面发送给我而不进行压缩&#34;。