在Google搜索中使用python机械化的问题

时间:2012-09-11 19:40:26

标签: python web-scraping mechanize

我最近发现了python库机制,我想用它来获取谷歌搜索的链接,但无法理解输出。这是我的代码片段:

import mechanize, cookielib
br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] 
br.set_handle_robots(False)
url = 'https://www.google.com/search?num=10&hl=en&site=&q=dog&oq=dog&aq=f&aqi=g10&aql=1&gs_sm=e'

response = br.open(url)

links = [link for link in br.links()]

运行正常,但输出如下:

[
Link(base_url='https://www.google.com/search?num=10&hl=en&site=&q=dog&oq=dog&aq=f&aqi=g10&aql=1&gs_sm=e', url='/support/websearch/bin/answer.py?answer=186645&form=bb&hl=en', text='Learn more', tag='a', attrs=[('href', '/support/websearch/bin/answer.py?answer=186645&form=bb&hl=en')]),
Link(base_url='https://www.google.com/search?num=10&hl=en&site=&q=dog&oq=dog&aq=f&aqi=g10&aql=1&gs_sm=e', url='http://www.google.com/intl/en/options/', text='More', tag='a', attrs=[('class', 'gbgt'), ('id', 'gbztm'), ('href', 'http://www.google.com/intl/en/options/'), ('onclick', 'gbar.tg(event,this)'), ('aria-haspopup', 'true'), ('aria-owns', 'gbd')]),
Link(base_url='https://www.google.com/search?num=10&hl=en&site=&q=dog&oq=dog&aq=f&aqi=g10&aql=1&gs_sm=e', url='/webhp?hl=en&tab=ww', text='', tag='a', attrs=[('href', '/webhp?hl=en&tab=ww'), ('onclick', 'gbar.logger.il(39)'), ('title', 'Go to Google Home')]),
...,
]

如何获取实际网址,而不是这种“点击我”式回复?

谢谢!

1 个答案:

答案 0 :(得分:2)

您已拉入页面上的每个链接,您需要将其过滤到相关的搜索结果链接。我认为这会做你想要的:

links = [link for link in br.links() if any(attr==('class','l') for attr in link.attrs)]

主搜索结果链接全部显示为class=l作为属性。我对[{1}}不熟悉,知道您是否可以在mechanize电话中执行此操作。