用 Python 抓取谷歌图片

sha*_*nen 5 python python-2.x web-scraping

我正在尝试学习 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
Run Code Online (Sandbox Code Playgroud)

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

小智 8

似乎谷歌最近从图像搜索结果中删除了元数据,即你不会rg_meta在 HTML 中找到。因此,soup.find_all("div",{"class":"rg_meta"}):不会返回任何东西。

我还没有找到解决方案。我相信谷歌为了防止抓取而做出这个改变。


foe*_*ver 5

我还没看到有人提到这个。这不是一个理想的解决方案,但如果你想要一些简单、有效并且不需要任何麻烦的设置,你可以使用 selenium。由于谷歌似乎故意阻止图像抓取,正如 Densus 提到的那样,这可能是对硒的不当使用,我不确定。

github 上有大量公开的、可用的 selenium google 图像抓取工具可供您查看和使用。事实上,如果你在 github 上搜索任何最近的 python 谷歌图像抓取器,我认为大多数(如果不是全部)都是 selenium 实现。

例如:https: //github.com/Msalmannnasir/Google_image_scraper

这个,只需下载 chromium 驱动程序并在代码中更新它的文件路径即可。