【问题标题】:Can't use read() for html2text?不能将 read() 用于 html2text?
【发布时间】:2015-12-27 00:01:01
【问题描述】:

我正在制作一个 Python 程序,用于在网页中搜索单词。虽然,当我尝试

website = urllib.request.urlopen(url)
content = website.read()
website.close()
test = html2text.html2text(content)
print(test)

我收到此错误:

test = html2text.html2text(content)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-    packages/html2text/__init__.py", line 840, in html2text
return h.handle(html)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-  packages/html2text/__init__.py", line 129, in handle
self.feed(data)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/html2text/__init__.py", line 125, in feed
data = data.replace("</' + 'script>", "</ignore>")
TypeError: a bytes-like object is required, not 'str'

我是 Python 新手,所以我不确定如何处理此错误。
Python 3.5,Mac。

【问题讨论】:

    标签: python python-3.x urllib


    【解决方案1】:

    decode()Charset 标头(reference)中发送的带有字符集的内容:

    resource = urllib.request.urlopen(url)
    content = resource.read()
    charset = resource.headers.get_content_charset()
    content = content.decode(charset)
    

    适合我(Python 3.5、Mac OS)。

    【讨论】:

    • 我收到了这个错误:charset = resource.headers.get_content_charset() AttributeError: module 'resource' has no attribute 'headers'
    • @Kamdroid 你确定要在 Python 3.5 上尝试吗?
    • 上面写着Python 2.7.10,很奇怪。我确实下载了 Python 3。也许是因为在下载 v3 之前我下载了 v2?虽然我在下载 v3.3 之前删除了 Python 2 文件夹。但我有标有 Python 3.5 的 Python 文件夹。
    • @Kamdroid 你试过以python3.5 运行它吗?
    • 嗯?我认为我只有 Python 3.5 应用程序。 Python 2 的目录是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    相关资源
    最近更新 更多