Python 3.x中導入urllib出現AttributeError: module 'urllib' has no attribute 'urlopen'

今天在研究Python爬蟲機制,起初遇到一些坑,把我本身的經歷寫出來,分享你們,少踩坑html

開始代碼入錯(錯誤代碼),不過我的建議有些坑踩一踩仍是有必要的,加深記憶python

import urllib

def run_demo():
    f=urllib.urlopen('http://www.baidu.com')
    print(f.readline())

if __name__=='__main__':
    run_demo()

執行結果以下url

Traceback (most recent call last):
  File "D:/gamepython/pabug/__init__.py", line 9, in <module>
    run_demo()
  File "D:/gamepython/pabug/__init__.py", line 5, in run_demo
    f=urllib.urlopen('http://www.baidu.com')
AttributeError: module 'urllib' has no attribute 'urlopen'spa

分析:紅色的部分表示找不到,通常出現這樣的問題有這麼幾種方式code

① 沒有引入對應的包,畢竟python的包多如屎htm

② 有人說是由於你的這個工程目錄下可能有一個本身定義的文件與urllib重名,致使上述代碼在引用時實際引用的是自定義的那個urllib,結果查找本身的項目文件夾下也沒有重名的文件。blog


可是這個問題就是特別的奇怪,都是不屬於上面的狀況,在網上查了後緣由以下it

Python3.X中應該用urllib.request。更改後就不會再出現這個錯誤了ast

import urllib.request

def run_demo():
    f=urllib.request.urlopen('http://www.baidu.com')
    print(f.read())

if __name__=='__main__':
    run_demo()

顯示結果以下class

b'<!DOCTYPE html>\n<!--STATUS OK-->\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\

相關文章
相關標籤/搜索