【问题标题】:AttributeError: 'HTTPResponse' object has no attribute 'replace'AttributeError:“HTTPResponse”对象没有“替换”属性
【发布时间】:2015-06-20 02:48:40
【问题描述】:

您好,我收到上述错误。为什么会弹出,我错过了什么以及如何解决它?谢谢

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

from html2text import html2text

sock = html2text(urllib2.urlopen('http://www.example.com')) 
htmlSource = sock.read()                            
sock.close()                                        
print (htmlSource)

我在 Windows 7 操作系统上运行 IDLE 3.4.3。

【问题讨论】:

  • 现在我得到 :TypeError: 'str' 不支持缓冲区接口

标签: python python-3.x httpresponse scrape


【解决方案1】:

html2text 期望 HTML 代码作为字符串传入 - 阅读响应:

source = urllib2.urlopen('http://www.example.com').read()
text = html2text(source)
print(text)

打印出来:

# Example Domain

This domain is established to be used for illustrative examples in documents.
You may use this domain in examples without prior coordination or asking for
permission.

[More information...](http://www.iana.org/domains/example)

【讨论】:

  • @user3115713 请仔细阅读此问题以及您之前提出的问题,看看是否有需要或应该接受的答案。谢谢!
【解决方案2】:

我想我找到了 Python 3.4 的解决方案。我刚刚将源代码解码为 UTF-8,它可以工作。

#!/usr/bin/python

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

from html2text import html2text

source=urllib2.urlopen('http://www.example.com').read() 
s=html2text(source.decode("UTF-8"))

print (s)

输出

# Example Domain

This domain is established to be used for illustrative examples in documents.
You may use this domain in examples without prior coordination or asking for
permission.

[More information...](http://www.iana.org/domains/example)

【讨论】:

  • 感谢它现在有效。我曾认为 python 3.x 似乎有自己的小天地。对于解决方案,为什么必须将其解码为 utf-8 以及您是如何采取这种方法的。谢谢
【解决方案3】:

替换是字符串的一个属性,你有一个文件对象

obj=urllib2.urlopen('http://www.example.com')
print obj

.

<addinfourl at 3066852812L whose fp = <socket._fileobject object at 0xb6d267ec>>

这个没问题。

#!/usr/bin/python

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

from html2text import html2text


source=urllib2.urlopen('http://www.example.com').read() 
s=html2text(source)

print s

输出

This domain is established to be used for illustrative examples in documents.
You may use this domain in examples without prior coordination or asking for
permission.

[More information...](http://www.iana.org/domains/example

【讨论】:

  • 仍然得到一个数据 = data.replace("' + 'script>", "") "TypeError: 'str' 不支持缓冲区接口"
  • 这很奇怪。我没有。
  • 您使用的是什么版本的 python,因为我在 Windows 7 操作系统上运行带有 IDLE 的 3.x。 ?
  • Ubuntu 上的 Python 2.7。是的,我用 Python 3.4 尝试了这个脚本,它给出了一个错误 "data = data.replace("' + 'script>", "") TypeError: expected bytes, bytearray or buffer compatible object" .我认为 html2text 模块与 Python 3.4 不兼容。 “打印(源)”工作正常,它只是无法从 html 中生成任何文本。很奇怪。
猜你喜欢
  • 2016-09-19
  • 2020-03-23
  • 2021-12-27
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多