我正在编写一个小的 Python 脚本来通过谷歌图像抓取图像。我已经设法将我想要的图像的网址放在一个方便的列表中。现在,我只需要抓住它们......
对于每个图像 url,我这样做:
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