已解决(Python3中urllib请求网页报错)
request = urllib.request.Request(url, headers=headers)
AttributeError: module ‘urllib’ has no attribute ‘request’
我的Python版本3.8,想用urllib库请求访问百度,报错代码如下:
import urllib
url = "https://www.baidu.com"
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0'}
request = urllib.request.Request(url, headers=headers)
html = urllib.request.urlopen(request).read()
print(html)
报错信息:可以看到两个request高亮着说明有问题
果然运行后报错了:
Traceback (most recent call last):
File "E:/Python学习/1.py", line 5, in <module>
request = urllib.request.Request(url, headers=headers)
AttributeError: module 'urllib' has no attribute 'request'
报错内容翻译:
属性错误: 模块“urllib”没有属性“request”
Python中出现AttributeError的错误主要有两类原因:
我的代码报错具体原因:查了一下资料是 python3 的 urllib 不会自动导入其under层的包,需要手动导入。
在Python3中手动导入request包,import urllib.request
就解决错误,修改代码:
import urllib
import urllib.request
url = "https://www.baidu.com"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0'}
request = urllib.request.Request(url, headers=headers)
html = urllib.request.urlopen(request).read()
print(html)
之前代码中的两个request高亮部分消失了:
运行成功: