【问题标题】:urlretrieve for image returns HTTP Error 403: Forbidden图片的 urlretrieve 返回 HTTP 错误 403:禁止访问
【发布时间】:2017-12-15 14:14:59
【问题描述】:

大家好,我正在尝试使用 BeautifulSoup 获取图像,但这样做时出现错误:

这是我的代码:

imgUrl = "https://www.residentadvisor.net/images/events/flyer/2017/7/no-0713-986042-front.jpg"
try:
    urlretrieve(imgUrl, "testPhytonImg.jpg")
except FileNotFoundError as err:
    print("something wrong with local path")
    print(err)   # something wrong with local path
except HTTPError as err:
    print("something wrong with url")
    print(err)  # something wrong with url

这是我得到的错误: HTTP Error 403: Forbidden

我得到这个的原因是什么?是否因为我做某事而阻止了对图像的访问,还是有其他方法可以解决这个问题?

【问题讨论】:

  • 这似乎托管在 Cloudflare 上,并且他们有非常“激进”的机器人检测。
  • 你会如何在 jpeg 上使用BeautifulSoup

标签: python beautifulsoup urlretrieve


【解决方案1】:

这对我有用。需要添加请求头

import urllib.request
url_address = "https://www.residentadvisor.net/images/events/flyer/2017/7/no-0713-986042-front.jpg"
headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
   'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
   'Accept-Encoding': 'none',
   'Accept-Language': 'en-US,en;q=0.8',
   'Connection': 'keep-alive'}
request_=urllib.request.Request(url_address,None,headers) #The assembled request
response = urllib.request.urlopen(request_)# store the response
#create a new file and write the image
f = open('00000001.jpg','wb')
f.write(response.read())
f.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多