【问题标题】:How do you get third link from BeautifulSoup result你如何从 BeautifulSoup 结果中获得第三个链接
【发布时间】:2016-10-12 22:41:33
【问题描述】:

我正在使用以下代码使用 BeautifulSoup 检索一堆链接。它返回所有链接,但我想获取第三个链接,解析那个链接,然后从那个链接中获取第三个链接,依此类推。如何修改下面的代码来实现这一点?

import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
    print tag.get('href', None)
    print tag.contents[0]

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    首先,您应该停止使用BeautifulSoup 第 3 版——它已经很老了,不再维护。切换到BeautifulSoup version 4。通过以下方式安装:

    pip install beautifulsoup4
    

    并将您的导入更改为:

    from bs4 import BeautifulSoup
    

    然后,您需要使用find_all() 并通过索引递归获取第三个链接,直到页面上没有第三个链接。这是一种方法:

    import urllib
    from bs4 import BeautifulSoup
    
    url = raw_input('Enter - ')
    
    while True:
        html = urllib.urlopen(url)
        soup = BeautifulSoup(html, "html.parser")
    
        try:
            url = soup.find_all('a')[2]["href"]
            # if the link is not absolute, you might need `urljoin()` here
        except IndexError:
            break  # could not get the 3rd link - exiting the loop
    

    【讨论】:

    • 感谢您回复 alecxe。在上面的代码中,“tags = soup('a') 返回一个列表。然后在执行“print”时我得到了很多链接。所以它似乎给了我所有的链接而不使用“find_all”。我很困惑这就是为什么我不能简单地打印标签[2],我认为它是循环迭代到的第三个链接。
    • @martinbshp 是的,soup() 是soup.find_all() 的快捷方式。是的,您需要得到href 属性值,如答案所示。
    • 哦!我现在明白了。您的回复促使我回过头来重新考虑这件事,看看标签是如何我需要查询的索引而不是 for 循环中的标签 var。谢谢。
    【解决方案2】:

    另一种选择是使用css selector,nth-of-type 来获取第三个锚点循环,直到 css 选择返回 None:

    import urllib
    from bs4 import BeautifulSoup
    
    url = raw_input('Enter - ')
    html = urllib.urlopen(url)
    soup = BeautifulSoup(html, "html.parser")
    a = soup.select_one("a:nth-of-type(3)")
    while a:
        html = urllib.urlopen(a["href"])
        soup = BeautifulSoup(html, "html.parser")
        a = soup.select_one("a:nth-of-type(3)")
    

    如果你想找到第三个有 href 属性的锚点,你可以使用"a:nth-of-type(3)[href]"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 2011-10-21
      • 2013-08-16
      • 2021-04-26
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 2022-08-24
      相关资源
      最近更新 更多