python写爬虫时出现AttributeError: module 'urllib' has no attribute 'urlopen'

首先需要检查自己的python环境是否与包相符合

出现AttributeError: module ‘urllib’ has no attribute ‘urlopen’
出现AttributeError: module ‘urllib’ has no attribute ‘request’
这种错误都是与导入包是否合适有关

在python3.X环境下包是这样的?

import urllib.request #导入的包是url.request

def getHtml(url):
    page = urllib.request.urlopen(url) #使用的方式是urllib.request.urlopen()
    html = page.read()
    return html

html = getHtml("http://www.baidu.com")

print (html)

导入的包是url.request
使用的方式是urllib.request.urlopen()

在python2.X环境下包是这样的?

import urllib #导入包为urllib 

def getHtml(url):
    page = urllib.urlopen(url) #使用方式urllib.urlopen
    html = page.read()
    return html

html = getHtml("http://www.baidu.com")

print html

导入的包是url
使用的方式是urllib.urlopen()

发布了52 篇原创文章 · 获赞 26 · 访问量 3424

猜你喜欢

转载自blog.csdn.net/weixin_43796685/article/details/102654689