HTTP错误403:使用urllib.request时禁止

HTTP错误403:使用urllib.request时禁止

问题描述:

我试图运行此代码,但所有时间我收到错误HTTP Error 403: ForbiddenHTTP错误403:使用urllib.request时禁止

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' 
+1

并且对开始SAVEFILE – WombatPM

+0

@WombatPM行缩进不当,但这似乎不是错误。看起来这是粘贴在这里的错误。但是,谢谢。 –

它看起来像你打开网址的两倍。两条建议:

  1. 为什么不直接使用requests模块呢?首先,安装:

    pip install requests 
    
  2. 使用with..as上下文管理器来处理文件I/O


import requests 

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' }  
resp_data = requests.get('http://google.com/search?q=test', headers=headers).text 

with open('newFile.txt', 'w') as savefile: 
    savefile.write(resp_data)