AttributeError:“HTTPResponse”对象没有“replace”属性

2024-04-18 18:05:20 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我发现上面的错误。为什么会突然出现,我错过了什么,我该如何克服?谢谢

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)

我在Windows7操作系统上运行Idle3.4.3。


Tags: fromimporthttprequestas错误urllib2urllib
3条回答

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)

Replace是字符串的属性,您有一个fileobject

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

我想我找到了Python3.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)

相关问题 更多 >