【问题标题】:Python3 urllib image retrevalPython3 urllib 图像检索
【发布时间】:2012-06-08 08:38:04
【问题描述】:

我正在编写一个小的 Python 脚本来通过谷歌图像抓取图像。我已经设法将我想要的图像的网址放在一个方便的列表中。现在,我只需要抓住它们......

对于每个图片网址,我都会这样做:

    print("Retrieving:{0}".format(sFinalImageURL))
    sExt = sFinalImageURL.split('.')[-1]
    #u = urllib.request.urlopen(sFinalImageURL)
    try:
        u = urllib.request.urlopen(sFinalImageURL)
    except:
        print("error: cannot retrieve image")
        continue
    raw_data = u.read()
    print("read {0} bytes".format(len(raw_data)))
    u.close()
    global sImagesFolder
    try:
        f = open("{0}/{1}_{2}.{3}".format(sImagesFolder,sImage,i,sExt),'wb')
        f.write(raw_data)
        f.close()
    except:
        print("couldn't write to {0}/{1}_{2}.{3}".format(sImagesFolder,sImage,i,sExt))
    print()

以下是我遇到的问题:

即使我可以直接在浏览器中打开这些 URL,尝试打开一些 URL 也会给我 403。因此,图像服务器不喜欢 HTTP 请求标头中的某些内容……有什么想法吗?

这是一些输出:

Retrieving:http://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Timba%2B1.jpg/220px-Timba%2B1.jpg

error: cannot retrieve image

Retrieving:http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg

error: cannot retrieve image
Retrieving:http://1.bp.blogspot.com/-7SsJ1n3RdoA/Tf07NOgD5nI/AAAAAAAAABo/tl8qLLIU01Y/s1600/english-shepherd-dog-0003.jpg

read 11123 bytes

Retrieving:http://completedogfood.net/wp-content/uploads/2010/07/complete-dog-food.bmp
read 419630 bytes

【问题讨论】:

  • 您能提供一些您正在使用的真实网址吗?
  • @BlaXpirit:当然。我把我的一些程序输出放在 Q 的底部
  • 您是否尝试设置用户代理?

标签: python-3.x urllib


【解决方案1】:

似乎维基百科只允许访问真实的浏览器。
这个问题可以通过指定一个真实浏览器的User-Agent字符串来解决,因为Python的urllib默认发送类似Python-urllib/3.2的东西。

这是一个有效的示例(使用我使用的浏览器的 User-Agent 字符串):

url = 'http://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Timba%2B1.jpg/220px-Timba%2B1.jpg'
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.168 Chrome/18.0.1025.168 Safari/535.19'
u = urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': user_agent}))

【讨论】:

  • 没必要假装自己是浏览器。只需将任何标识您的脚本的内容放入用户代理字段即可。 “不要使用您的客户端库提供的默认用户代理,而是制作一个自定义标头来标识您的脚本或服务并提供某种与您联系的方式(例如,电子邮件地址)。” mediawiki.org/wiki/API:Main_page#Identifying_your_client
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2015-09-01
  • 2019-05-14
相关资源
最近更新 更多