【问题标题】:Unable to find all links with BeautifulSoup to extract links from a website (Link identification)无法使用 BeautifulSoup 找到所有链接以从网站中提取链接(链接识别)
【发布时间】:2016-09-19 22:01:09
【问题描述】:

我正在使用此处的代码 (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。但我仍然有同样的行为。

感谢您的帮助

【问题讨论】:

  • 我实际上没有在此页面上看到“职业”链接 - 我们正在查看同一页面吗?..
  • 您将通过查看此处的站点地图看到“职业”链接bestwestern.com.au/sitemap

标签: python-2.7 hyperlink beautifulsoup html5lib


【解决方案1】:

好的,这是一个老问题,但我在搜索中偶然发现了它,看起来它应该相对容易完成。我确实从 httplib2 切换到 requests。

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)

【讨论】:

    【解决方案2】:

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

    pip install beautifulsoup4
    

    另一个问题是主页上没有“职业”链接,但“站点地图”页面上有一个 - 请求它并使用默认的 html.parser 解析器进行解析 - 你会看到“职业”链接打印在其他中:

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

    请注意我是如何将“必须有 href”规则移至汤过滤器的。

    【讨论】:

    • 我有 BeautifulSoup 的第 4 版,但仍然找不到链接。我不知道默认的解析器是不是Python内置的HTML解析器,但我认为问题可能来自那方面。
    • 这是 Python 内置 HTML 解析器的另一个常见问题,它有时会跳过它不理解的标签。同样,解决方案是安装 lxml 或 html5lib。”所以我安装了html5lib。但我仍然有同样的行为。
    • @BND nono,正如我所问的那样-主页上没有“职业”链接,但sitemap 页面上有一个-更新了答案中的代码-适用于我原样并打印“carrers”链接。
    • 感谢您的帮助。它也适用于我。但我真的不明白。为什么在主页bestwestern.com.au找不到链接?
    • 感谢您的帮助。它也适用于我。但我现在明白了。该代码仅提取页面上的链接而不是所有网站上的链接?我正在寻找做第二个的事情。
    猜你喜欢
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2021-11-26
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多