1

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

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')]),
...,
]

如何获取实际 URL,而不是这种“点击我”样式响应?

谢谢!

4

1 回答 1

2

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

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

主要的搜索结果链接似乎都有class=l一个属性。我不太熟悉,mechanize不知道您是否可以在links()通话中执行此操作。

于 2012-09-12T06:49:29.227 回答