前言
最近更新了Python版本,準備寫個爬蟲,意外的發現urllib庫中屬性不存在urlopen,于是各種google,然后總結一下給出解決方案
問題的出現
AttributeError: 'module' object has no attribute 'urlopen'
問題的解決途徑
我們先來看下官方文檔的解釋:
a new urllib package was created. It consists of code from urllib, urllib2, urlparse, and robotparser. The old modules have all been removed. The new package has five submodules: urllib.parse, urllib.request, urllib.response, urllib.error, and urllib.robotparser. The urllib.request.urlopen() function uses the url opener from urllib2. (Note that the unittests have not been renamed for the beta, but they will be renamed in the future.)
也就是說官方3.0版本已經把urllib2,urlparse等五個模塊都并入了urllib中,也就是整合了。
正確的使用方法
import urllib.request url="http://www.baidu.com" get=urllib.request.urlopen(url).read() print(get)
結果示意圖:
其實也是可以換個utf-8的編碼讓讀取出來的源碼更正確的,但這已經是番外的不再提了。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林站長站的支持。
新聞熱點
疑難解答