【问题标题】:Python encoded string is still in binary formatPython 编码的字符串仍然是二进制格式
【发布时间】:2014-12-05 11:35:43
【问题描述】:

我正在尝试使用 urllib3 和漂亮的汤进行一些网站抓取。 Python 3 编码/解码让我大吃一惊。这是我的代码

r = http.request('GET', 'https://www.************************.jsf')

if(r.status == 200):
    page = r.data.decode('utf-8')
    soup = BeautifulSoup(page)  

    print(soup.prettify())
    #This prints - [Decode error - output not utf-8]
    #              [Decode error - output not utf-8]

    print(soup.prettify().encode('utf-8'))
    #This prints the data but with binary mark
    # b'<!DOCTYPE html PUBLIC "-//W3C//D.......
    #..........................................'

由于我在调用美丽汤之前已经完成了r.data.decode('utf-8')的解码,为什么我需要再次对其进行编码,为什么即使将其转换为字符串后它仍然显示b''标记

【问题讨论】:

  • data 属性未记录在案。为什么也没有getresponse() 电话?
  • 我在 readthedocs 上阅读了 urllib3 文档。找不到对 getresponse() 的任何引用。此外,数据属性几乎是访问那里的响应内容的唯一方法..https://urllib3.readthedocs.org/en/latest/index.html。也许我错过了什么。

标签: python-3.x character-encoding beautifulsoup urllib3


【解决方案1】:

b'xxx' 是二进制类型值的表示(字节序列——这是.encode() 的自然结果。如果对象不是字符串,print() 函数会自动将对象转换为其表示形式。

尝试将调试信息写入文件。 print 函数在输出到支持某些字符集/编码的控制台时可能存在问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多