【问题标题】:Problems using python mechanize with Google Searches在 Google 搜索中使用 python mechanize 的问题
【发布时间】:2012-09-11 19:40:26
【问题描述】:

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

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,而不是这种“点击我”样式的响应?

谢谢!

【问题讨论】:

    标签: python web-scraping mechanize


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 2016-12-02
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      相关资源
      最近更新 更多