我写了一个脚本来从谷歌图片搜索中下载图片,我目前正在下载 100 张原始图片
我在stackoverflow上写的原始脚本回答
Python - Download Images from google Image search?
我将详细解释我如何使用 urllib2 和 BeautifulSoup 从 Google 图片搜索中抓取原始图片的 url
例如,如果你想从谷歌图像搜索中抓取电影终结者 3 的图像
query= "Terminator 3"
query= '+'.join(query.split()) #this will make the query terminator+3
url="https://www.google.co.in/search?q="+query+"&source=lnms&tbm=isch"
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"
}
req = urllib2.Request(url,headers=header)
soup= urllib2.urlopen(req)
soup = BeautifulSoup(soup)
上面的变量汤包含请求页面的 html 代码,现在我们需要提取图像,您必须在浏览器中打开网页并检查图像上的元素
在这里你会找到包含 url 图片的标签
例如,对于谷歌图片,我发现 "div",{"class":"rg_meta"} 包含图片链接
你可以搜索 BeautifulSoup 文档
print soup.find_all("div",{"class":"rg_meta"})
你会得到一个结果列表
<div class="rg_meta">{"cl":3,"cr":3,"ct":12,"id":"C0s-rtOZqcJOvM:","isu":"emuparadise.me","itg":false,"ity":"jpg","oh":540,"ou":"http://199.101.98.242/media/images/66433-Terminator_3_The_Redemption-1.jpg","ow":960,"pt":"Terminator 3 The Redemption ISO \\u0026lt; GCN ISOs | Emuparadise","rid":"VJSwsesuO1s1UM","ru":"http://www.emuparadise.me/Nintendo_Gamecube_ISOs/Terminator_3_The_Redemption/66433","s":"Screenshot Thumbnail / Media File 1 for Terminator 3 The Redemption","th":168,"tu":"https://encrypted-tbn2.gstatic.com/images?q\\u003dtbn:ANd9GcRs8dp-ojc4BmP1PONsXlvscfIl58k9hpu6aWlGV_WwJ33A26jaIw","tw":300}</div>
上面的结果包含指向我们图片网址的链接
http://199.101.98.242/media/images/66433-Terminator_3_The_Redemption-1.jpg
您可以按如下方式提取这些链接和图片
ActualImages=[]# contains the link for Large original images, type of image
for a in soup.find_all("div",{"class":"rg_meta"}):
link , Type =json.loads(a.text)["ou"] ,json.loads(a.text)["ity"]
ActualImages.append((link,Type))
for i , (img , Type) in enumerate( ActualImages):
try:
req = urllib2.Request(img, headers={'User-Agent' : header})
raw_img = urllib2.urlopen(req).read()
if not os.path.exists(DIR):
os.mkdir(DIR)
cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
print cntr
if len(Type)==0:
f = open(DIR + image_type + "_"+ str(cntr)+".jpg", 'wb')
else :
f = open(DIR + image_type + "_"+ str(cntr)+"."+Type, 'wb')
f.write(raw_img)
f.close()
except Exception as e:
print "could not load : "+img
print e
瞧,现在你可以使用这个脚本从谷歌搜索中下载图像。或用于收集训练图像
您可以在此处获取完整的脚本
https://gist.github.com/rishabhsixfeet/8ff479de9d19549d5c2d8bfc14af9b88