Urllib.request.urlopen().read 不起作用



最后一行代码出错。

import re
import urllib.request
url="https://www.google.com/search?q=google&tbm=fin#scso=_GYPEXIHYJs6gtQXFn7i4Aw2:0"
data=urllib.request.urlopen(url).read()

网址="https://www.google.com/search?q=google&tbm=fin#scso=_GYPEXIHYJs6gtQXFn7i4Aw2:0" data=urllib.request.urlopen(url).read() 回溯(最近一次调用): 文件 ",第 1 行,在 data=urllib.request.urlopen(url).read() 文件 "C:\Users\SHARM\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 222 行,在 urlopen 中 返回 opener.open(URL, data, timeout) 文件 "C:\Users\SHARM\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 531 行,打开 响应 = 甲基(要求,响应) 文件 "C:\Users\SHARM\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 641 行,http_response 'http', request, response, code, msg, hdrs) 文件 "C:\Users\SHARM\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 569 行,错误 返回self._call_chain(*参数) 文件 "C:\Users\SHARM\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 503 行,_call_chain 结果 = func(*args) 文件 "C:\Users\SHARM\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 649 行,http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP 错误 403: 禁止

我想打开网址。当我手动打开时,URL 有效。我不明白为什么我会收到此错误,此错误是什么意思?

HTTP Error 403: Forbidden错误可能是由阻止机器人用户代理的远程服务器安全性引起的,更改用户代理标头将修复此错误。

from urllib.request import Request, urlopen
url="https://www.google.com/search?q=google&tbm=fin#scso=_GYPEXIHYJs6gtQXFn7i4Aw2:0" 
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
data=urlopen(req).read()

最新更新