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

Unable to find all links with BeautifulSoup to extract links from a website (Link identification)

我正在使用此处找到的这段代码 (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() returns [] 或 find() returns None。这是 Python 内置 HTML 解析器的另一个常见问题,它有时会跳过它不理解的标签。同样,解决方案是安装 lxml 或 html5lib。” 所以我安装了html5lib。但我仍然有相同的行为。

感谢您的帮助

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

pip install beautifulsoup4

还有一个问题就是主页上没有"careers" link,但是"sitemap"页面上有-请求它并用默认的[=14解析=] 解析器 - 你会看到 "careers" link 等印刷:

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

请注意我是如何将 "has to have href" 规则移至滤汤器的。

好的,这是一个老问题,但我在搜索中偶然发现了它,看起来它应该相对容易完成。我确实从 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)