[英]How to get round the HTTP Error 403: Forbidden with urllib.request using Python 3
[英]HTTP Error 403: Forbidden when using urllib.request
我嘗試運行此代碼,但始終收到錯誤HTTP Error 403: Forbidden
。
import urllib.request
try:
url = urllib.request.urlopen('http://google.com/search?q=test')
headers = {}
headers['User-Agent'] ='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
resp_Data = resp.read()
savefile = open('newFile.txt', 'w')
savefile.write(str(resp_Data))
savefile.close()
except Exception as e:
print(str(e))
有人可以在這段代碼中為我提供幫助,因為我在這里找不到解決方案嗎?
更改此行
url = urllib.request.urlopen('http://google.com/search?q=test')
至
url = 'http://google.com/search?q=test'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.