html 代码结果(UI)在使用 Python 编写的 google 图像抓取与网络浏览器之间存在差异

Different html code result(UI) between using google image scraper written in Python vs. web browser

我使用 urllib2 和 BeautifulSoup 库在 Python 中编写了一个 Google 图像抓取工具,它使用 URL 发送一个包含查询的搜索请求,然后获取 links 到前 10 张图像。我需要的是图片的直接link,例如:

http://images.mentalfloss.com/sites/default/files/styles/insert_main_wide_image/public/einstein1_7.jpg

当我使用浏览器(即 Chrome)搜索查询并查看图像搜索结果页面的 HTML 代码时,该代码包括直接 URL图片(如上)以及包含图片的页面的 URL:

http://mentalfloss.com/article/49222/11-unserious-photos-albert-einstein

但是,我使用 python 抓取器获得的搜索结果页面的 HTML 代码不包含直接 URL 图像,而仅包含 URL 到包含图像的原始页面。当我保存结果 HTML 并在我的浏览器上查看文件时,它显示了一些旧的 Google 图片搜索 UI。单击其中一个缩略图会导致 'Your file was not found. It may have been moved or deleted' 错误。

我知道使用浏览器应用程序和使用 python 库发送 URL 请求时的搜索设置不同,但我不确定是哪个参数导致了这种差异。

我将图像附加到两个不同的结果 UIs(上面是我的 python 爬虫的结果 HTML 页面,底部是 Chrome 的结果浏览器)

这是我的脚本的一部分:

def search_image_google(name):
    google_url = "https://www.google.com/search?btnG=Search&site=webhp&tbm=isch&source=hp&q={}"
    headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
    url = google_url.format(urllib2.quote(name+' face'))

    try:
        page = requests.get(url).text
        soup = BeautifulSoup(page, 'html.parser')
        result = soup.prettify("utf-8")
        with open('output.html', 'wb') as file:
            file.write(result)

        cnt = 0
        for link in soup.find_all('table', class_ = 'images_table'):
            for child in link.contents:
                for row in child:
                    if cnt > 9:
                        break;
                    else:
                        img_link = str(row.a['href'])[7:]
                        cnt += 1
                        print(img_link)

    except Exception as e:
        print('Exception: %s' % str(e))

请帮忙!

尝试检查您的浏览器发送的所有 HTTP headers,您可能需要的不仅仅是 user-agent。

另外记得尊重本站的/robots.txt

抱歉这么说,但是您将很难使用这种方法。

Google 将根据多种因素(用户代理、浏览器功能、您是否登录,甚至连接速度...)为您提供不同的 HTML。

您甚至可以连接到不同的 Google 服务器,这些服务器的代码 运行 版本略有不同,因此发送给您的 HTML 也会略有不同。除此之外,Google 作为正常开发的一部分不时更改他们的标记...

因此,这些都是自然发生的事实,它们会阻碍您抓取其结果的能力。

补充一点:这违反了 Google 的条款和条件,因此一旦他们检测到您(验证码等),他们也会采用爬行反制措施,这使得它更难做到。

这是因为 Google 希望您使用 Google 自定义搜索。

https://developers.google.com/custom-search/

它具有图像搜索功能。你应该调查一下,希望它能解决你的问题。