我试图解析谷歌图片搜索结果的html并获取图片的原始链接。到目前为止,我成功地编写了一个python代码,使用python的mechanize和BeautifulSoup获取谷歌搜索的HTML。
查看谷歌搜索结果html源代码我发现谷歌正在使用类rg_meta
存储原始图像的网址的双重编码。但我从Mechnaize收到的HTML不包含任何此类课程。事实上,整个新网页正在通过机械化返回。
我知道谷歌的图片搜索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
答案 0 :(得分:0)
感谢您的尝试,但我不得不转移到urllib2来解决这个问题, 以下代码正在解析谷歌搜索页面的图片链接。
search = search.replace(" ","%20")
site= "http://www.google.co.in/search?q="+search+"&tbm=isch&tbs=isz:l"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
QtGui.qApp.processEvents()
req = urllib2.Request(site, headers=hdr)
try:
QtGui.qApp.processEvents()
page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
QtGui.qApp.processEvents()
content = page.read()
#print content
soup = BeautifulSoup(content)
results = soup.findAll("a")
linkarray = soup.find_all(attrs={"class": "rg_meta"})
#print linkarray
refer_rl=[]
total=len(linkarray)
i=0
for divs in linkarray:
i=i+1
stri=str(divs)
refer_url=stri.split('%3B')
try:
QtGui.qApp.processEvents()
url=urllib.unquote(refer_url[2]).decode('utf8')
url=urllib.unquote(url).decode('utf8')
#os.system('wget '+url)
#f = open('links.txt', 'a')
#f.write(url+'\n')
form.textBrowser.append(url)
form.progressBar.setProperty("value", i*100/total)
time.sleep(0.05)
except:
continue
#os.system('aria2c -i links.txt -x 16')
#os.system('rm links.txt')
print "All good, you can download now"
答案 1 :(得分:0)
import mechanize
br = mechanize.Browser()
br.open(<yoursitehere>)
images = re.findall("src=\"[^\"]{8,240}", br.response().read())
for i in images: print i
br.close()
您需要稍微过滤一下结果,然后根据特定网站的HTML修改RE