2015-06-20 75 views
0

嗨,我得到了上述錯誤。爲什麼會彈出,我錯過了什麼,我該如何解決它?謝謝AttributeError:'HTTPResponse'對象沒有屬性'替換'

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。

+0

現在即時得到:類型錯誤: 'STR' 不支持緩衝區接口 – user3115713

回答

2

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) 
+0

我明白了。謝謝 。 – user3115713

+0

@ user3115713請仔細閱讀本問題以及之前提出的問題,看看是否有需要或應該接受的答案。謝謝! – alecxe

0

替換爲的字符串屬性,你有一個文件對象

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 
+0

仍然得到一個數據= data.replace(「」,「」)「TypeError:'str'不支持緩衝區接口」 – user3115713

+0

這很奇怪。我不。 –

+0

在Windows 7操作系統上,我使用了什麼版本的Python來運行帶有IDLE的3.x。 ? – user3115713

0

我想我發現爲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) 
+0

感謝它現在的作品。我認爲python 3.x似乎有一個屬於自己的小世界。爲了解決這個問題,爲什麼必須將它解碼爲utf-8,並且你是如何得到這種方法的。謝謝 – user3115713