href给出的Google搜索网址是错误的

时间:2013-04-15 17:01:48

标签: python html web beautifulsoup

谷歌搜索似乎会提供以下网址:

/url?q=  "URL WOULD BE HERE"    &sa=U&ei=9LFsUbPhN47qqAHSkoGoDQ&ved=0CCoQFjAA&usg=AFQjCNEZ_f4a9Lnb8v2_xH0GLQ_-H0fokw

当受到BeautifulSoup的html解析时。

我使用soup.findAll('a')然后使用['href']来获取链接。

更具体地说,我使用的代码如下:

import urllib2
from BeautifulSoup import BeautifulSoup, SoupStrainer
import re

main_site = 'https://www.google.com/'
search = 'search?q=' 
query = 'pillows'
full_url = main_site+search+query
request = urllib2.Request(full_url, headers={'User-Agent': 'Chrome/16.0.912.77'})
main_html = urllib2.urlopen(request).read()

results = BeautifulSoup(main_html, parseOnlyThese=SoupStrainer('div', {'id': 'search'}))
try:
    for search_hit in results.findAll('li', {'class':'g'}):
        for elm in search_hit.findAll('h3',{'class':'r'}):
            for a in elm.findAll('a',{'href':re.compile('.+')}):
                print a['href']

except TypeError:
    pass

此外,我在其他网站上发现a['href']可能会返回/dsoicjsdaoicjsdcj之类的内容,其中链接会将您带到website.com/dsoicjsdaoicjsdcj。 我知道如果是这种情况我可以简单地连接它们,但我觉得不应该是我应该改变我解析的方式并根据我正在寻找的网站来处理a['href']在。有没有更好的方法来获得此链接?我需要考虑一些JavaScript吗?当然,BeautifulSoup中有一种简单的方法可以从a获取完整的html?

1 个答案:

答案 0 :(得分:0)

SoupStrainer('div', {'class': "vsc"})
当你这样做时,

不会返回任何原因:

print main_html

并搜索“vsc”,没有结果