无法找到BeautifulSoup的所有链接以从网站中提取链接(链接标识)

时间:2016-09-19 22:01:09

标签: python-2.7 hyperlink beautifulsoup html5lib

我正在使用此处的代码(retrieve links from web page using python and BeautifulSoup)从网站中提取所有链接。

import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request('http://www.bestwestern.com.au')

for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
    if link.has_attr('href'):
        print link['href']

我正在使用此网站http://www.bestwestern.com.au作为测试。 不幸的是,我注意到代码没有提取一些链接,例如这个http://www.bestwestern.com.au/about-us/careers/。我不知道为什么。 在页面的代码中,这是我发现的。

<li><a href="http://www.bestwestern.com.au/about-us/careers/">Careers</a></li>

我认为提取器通常应该识别它。 在BeautifulSoup文档中,我可以读到:“最常见的意外行为类型是您无法找到您知道的文档中的标记。你看到它进入,但find_all()返回[]或find()返回None。这是Python内置HTML解析器的另一个常见问题,它有时会跳过它不理解的标签。同样,解决方案是安装lxml或html5lib。“ 所以我安装了html5lib。但我仍然有同样的行为。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

一个问题是 - 您使用的BeautifulSoup版本3已不再维护。您需要升级到BeautifulSoup version 4

pip install beautifulsoup4

另一个问题是没有&#34;职业生涯&#34;链接在主页面上,但在&#34; sitemap&#34;页面 - 请求它并使用默认的html.parser解析器进行解析 - 您将看到&#34;职业生涯&#34;链接打印其他:

import requests
from bs4 import BeautifulSoup, SoupStrainer

response = requests.get('http://www.bestwestern.com.au/sitemap/')

for link in BeautifulSoup(response.content, "html.parser", parse_only=SoupStrainer('a', href=True)):
    print(link['href'])

请注意我是如何移动&#34;必须有href&#34;统治汤滤网。

答案 1 :(得分:1)

好的,所以这是一个老问题,但我在搜索中偶然发现它,看起来它应该相对简单。我确实从httplib2切换到了请求。

import requests
from bs4 import BeautifulSoup, SoupStrainer
baseurl = 'http://www.bestwestern.com.au'

SEEN_URLS = []
def get_links(url):
    response = requests.get(url)
    for link in BeautifulSoup(response.content, 'html.parser', parse_only=SoupStrainer('a', href=True)):
        print(link['href'])
        SEEN_URLS.append(link['href'])
        if baseurl in link['href'] and link['href'] not in SEEN_URLS:
            get_links(link['href'])

if __name__ == '__main__':
    get_links(baseurl)