HTTP错误403:禁止使用Python3&如何在抓取时更改IP

时间:2018-03-17 22:13:41

标签: python http-status-code-403

以下是我的代码。我想从Google财经获取历史数据,我尝试了一些方法来修复它。但它仍然无法奏效。我想这可能是因为Google财经阻止了我的IP。如果是的话,有什么解决方案吗?

url='http://finance.google.com/finance/historical?q=AMZN'
headers = {'Accept': 
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','User-Agent':'Mozilla/5.0'}
context = ssl._create_unverified_context()
htmlll=urllib.request.Request(url,headers=headers)
html = urllib.request.urlopen(htmlll,context=context).read().decode()
datalist=html.splitlines()
name = datalist[2].split('>')[2].split(':')[0].replace('amp;','')
print(name)

错误如下

Traceback (most recent call last):
File "C:/Users/admin/Desktop/Price & Volume Database/Global Intraday Pricing Data/Asia Intraday Pricing/test.py", line 30, in <module>
html = urllib.request.urlopen(htmlll,context=context).read().decode()
File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 162, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 471, in open
response = meth(req, response)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 581, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35-
32\lib\urllib\request.py", line 509, in error
return self._call_chain(*args)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 443, in _call_chain
result = func(*args)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 589, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

我添加了标题,网址也有效。我找不到它的错误。非常感谢你的帮助!

0 个答案:

没有答案