我试图解析谷歌图像搜索结果的HTML,并获得图像的原始链接
到目前为止,我成功地编写了一个Python代码,使用Python的Mechanize和BeautifulSoup获取Google搜索的HTML
查看Google的搜索结果HTML源代码,我发现Google正在使用类rg_meta
将原始图像URL的双重编码存储在一个div中,但我从Mechanize收到的HTML不包含任何此类。事实上,整个新网页是通过Mechanize返回的
我知道谷歌的图像搜索API,但我需要用这种方式解析HTML。我做错了什么?我可以将Mechanize屏蔽为Chrome或其他浏览器吗
这是我尝试的一个片段。它没有返回任何内容:
import urllib
import mechanize
from bs4 import BeautifulSoup
from urlparse import urlparse
search = "cars"
browser = mechanize.Browser()
browser.set_proxies({"https": "10.0.2.88:3128"})
browser.set_handle_robots(False)
browser.addheaders = [('User-agent','Mozilla')]
html = browser.open("https://www.google.co.in/search?&source=lnms&tbm=isch&sa=X&q="+search+"&oq="+search)
htmltext=html.read()
print htmltext
img_urls = []
formatted_images = []
soup = BeautifulSoup(htmltext)
#results = soup.findAll("a")
results = soup.findAll("div", { "class" : "rg_meta" })
print results
您需要对结果进行一些过滤,并根据特定站点的HTML修改RE
为了使用
requests
和beautifulsoup
库刮取全分辨率图像URL,需要使用regex
从页面源代码中刮取数据基本解释:
代码和full example in the online IDE也将图像下载到文件夹:
或者,您可以通过使用SerpApi中的Google Images API来实现相同的功能。这是一个免费的付费API
这种情况的不同之处在于,您不必使用正则表达式来匹配和提取页面源代码中所需的数据,相反,您只需迭代结构化JSON即可更快地获得所需的数据
要集成以实现目标的代码:
另外,我写了一篇更深入的博文,内容是关于如何刮Google Images和how to reduce the chance of being blocked while web scraping search engines
感谢您的尝试,但我必须切换到urllib2来解决此问题, 下面的代码正在解析google搜索页面的图像链接
相关问题 更多 >
编程相关推荐