【问题标题】:HTTP Error 403: Forbidden when using urllib.requestHTTP 错误 403:使用 urllib.request 时被禁止
【发布时间】:2017-08-27 06:10:21
【问题描述】:

我尝试运行此代码,但一直收到错误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))

任何人都可以在这段代码中帮助我吗,因为我在这里找不到解决方案?

【问题讨论】:

    标签: python python-3.x urllib


    【解决方案1】:

    改变这一行

    url = urllib.request.urlopen('http://google.com/search?q=test')
    

    url = 'http://google.com/search?q=test'
    

    【讨论】:

    • 而且savefile开头的行缩进不正确
    • @WombatPM 但这似乎不是错误。好像是贴在这里的时候出错了。不过,谢谢。
    猜你喜欢
    • 2023-03-12
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2015-11-29
    • 2018-01-03
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多