gpt4 book ai didi

python - 用 Python 抓取谷歌图片

转载 作者:行者123 更新时间:2023-12-03 15:35:31 25 4
gpt4 key购买 nike

我正在尝试学习 Python 抓取并遇到了一个程序,可以从 Google 图片搜索结果中抓取一定数量的图片

我将其更改为 5 张图像,它工作了一段时间,但最近停止工作并显示输出,例如 there are 0 images

import requests
import re
import urllib2
import os
import cookielib
import json

def get_soup(url,header):
return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')


query = raw_input("query image")# you can change the query for the image here
image_type="ActiOn"
query= query.split()
query='+'.join(query)
url="https://www.google.com/search?q="+query+"&source=lnms&tbm=isch"
print url
#add the directory for your image here
DIR="C:\Users\mynam\Desktop\WB"
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"
}
soup = get_soup(url,header)


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

print "there are total" , len(ActualImages),"images"

if not os.path.exists(DIR):
os.mkdir(DIR)
DIR = os.path.join(DIR, query.split()[0])

if not os.path.exists(DIR):
os.mkdir(DIR)
###print images
for i , (img , Type) in enumerate(ActualImages[0:5]):
try:
req = urllib2.Request(img, headers={'User-Agent' : header})
raw_img = urllib2.urlopen(req).read()

cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
print cntr
if len(Type)==0:
f = open(os.path.join(DIR , image_type + "_"+ str(cntr)+".jpg"), 'wb')
else :
f = open(os.path.join(DIR , image_type + "_"+ str(cntr)+"."+Type), 'wb')


f.write(raw_img)
f.close()
except Exception as e:
print "could not load : "+img
print e

没有错误日志,文件被创建并且它是空的。 ActualImages数组由于某种原因保持为空。

最佳答案

Google 好像有 最近 从图片搜索结果中删除元数据,即您不会找到 rg_meta在 HTML 中。因此,soup.find_all("div",{"class":"rg_meta"}):不会返回任何东西。
我还没有找到解决方案。我相信 Google 做出此更改的真正目的是防止 刮刮 .

关于python - 用 Python 抓取谷歌图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60095629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com