【问题标题】:decode response of get request for persian websites解码波斯网站获取请求的响应
【发布时间】:2020-01-27 13:11:48
【问题描述】:

我正在编写发送请求和获取网站响应以及解析它的内容的函数...... 但是当我向波斯网站发送请求时,它无法解码它的内容

def gather_links(page_url):
    html_string = ''
    try:
        response = urlopen(page_url)
        if 'text/html' in response.getheader('Content-Type'):
            html_bytes = response.read()
            html_string = html_bytes.decode("utf-8")    
    except Exception as e:
        print(str(e))

显示此错误,例如 https://www.entekhab.ir/

'utf-8' 编解码器无法解码位置 1 中的字节 0x8b:无效的起始字节

如何更改解码此类网站的代码?

【问题讨论】:

    标签: python gzip decoding transfer-encoding


    【解决方案1】:

    你应该使用requests而不是urllib。

    import requests
    
    response = requests.get('https://www.entekhab.ir/')
    print(response.text)
    

    【讨论】:

    • ye 它的工作更好并且工作正常...请求库有什么不同的 urllib.request 包?
    • requests 更好,每个人都使用它。
    【解决方案2】:

    问题是url的内容是用gzip压缩的,urlopen好像默认不处理:

    >>> r = request.urlopen('https://www.entekhab.ir/')
    >>> print(r.info())
    Server: sepehr-proxy-1.2-rc3
    Content-Type: text/html; charset=utf-8
    Expires: Mon, 26 Jul 1997 05:00:00 GMT
    Cache-Control: post-check=0, pre-check=0
    Pragma: no-cache
    Connection: close
    Content-Length: 81269
    Date: Sat, 28 Sep 2019 14:41:49 GMT
    Content-Encoding: gzip
    

    因此,需要在解码前解压响应:

    >>> import gzip
    >>> bs = gzip.decompress(r.read())
    >>> bs.decode('utf-8')[:113]
    '<!-- 2019/09/28 18:16:08 --><!DOCTYPE html> <html lang="fa-IR" dir="rtl"> <head>           <meta charset="utf-8">'
    

    正如用户 askaroni 的回答所指出的,requests 包会自动处理这种情况,甚至 Python urllib 文档也推荐使用它。不过,了解为什么无法立即解码响应是很有用的。

    【讨论】:

    • 非常感谢...您的回答如此专业,您从根本上解决了问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 2019-12-12
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多