用python抓取google图像

问题描述 投票:0回答:1

[我正在尝试学习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已

最近

从图像搜索结果中删除了元数据,即您在HTML中找不到rg_meta。因此,soup.find_all("div",{"class":"rg_meta"}):将不会返回任何内容。我还没有找到解决方案。我相信Google这样做是为了防止报废。
python web-scraping python-2.x
1个回答
0
投票
似乎Google已

最近

© www.soinside.com 2019 - 2024. All rights reserved.