Python3 urllib image retreval

坚强是说给别人听的谎言 提交于 2019-12-01 21:02:34

问题


I'm writing a small Python script to grab images via google images. I've managed to get things up to the point where I have the urls of the images I want in a handy list. Now, I just need to grab them...

for each image url i do this:

    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()

Here are the problems I'm coming up against:

trying to open some off the URLs gives me 403 even though I can open the URLs straight in my browser. So there's something in the HTTP request header that the image server doesn't like... any ideas?

Here's some of the output:

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

回答1:


It seems like Wikipedia only allows access to real browsers.
The problem can be solved by specifying a User-Agent string of a real browser, because Python's urllib sends something like Python-urllib/3.2 by default.

Here's an example that works (with User-Agent string of the browser that I use):

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}))


来源:https://stackoverflow.com/questions/10945542/python3-urllib-image-retreval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!