【问题标题】:Find third occurring `<p>` tag using with Beautiful Soup使用 Beautiful Soup 查找第三个出现的 `<p>` 标记
【发布时间】:2016-09-06 02:32:58
【问题描述】:

正如标题所示,我试图了解如何找到网站的第三个出现的&lt;p&gt;(例如,我使用了以下网站:http://www.musicmeter.nl/album/31759)。

使用this question的答案,我尝试了以下代码

from bs4 import BeautifulSoup
import requests
html = requests.get("http://www.musicmeter.nl/album/31759").text    # get HTML from http://www.musicmeter.nl/album/31759
soup = BeautifulSoup(html, 'html5lib')                              # Get data out of HTML

first_paragraph = soup.find('p')    # or just soup.p

print "first paragraph:", first_paragraph

second_paragraph = first_paragraph.find_next_siblings('p')

print "second paragraph:", second_paragraph

third_paragraph = second_paragraph.find_next_siblings('p')

print "third paragraph:", third_paragraph

但是这段代码导致第三段出现以下错误:

Traceback (most recent call last):
  File "page_109.py", line 21, in <module>
    third_paragraph = second_paragraph.find_next_siblings('p')
AttributeError: 'ResultSet' object has no attribute 'find_next_siblings'

我试图查找错误,但我无法找出问题所在。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    您正在使用 siblings 即复数,因此您得到了一个 ResultSet/list ,您无法在其上调用 .find_next_siblings

    如果你想要下一段,你会使用 sibling 而不是 siblings

    second_paragraph = first_paragraph.find_next_sibling('p')
    
    print "second paragraph:", second_paragraph
    
    third_paragraph = second_paragraph.find_next_sibling('p')
    

    可以链接的:

    third_paragraph = soup.find("p").find_next_sibling('p').find_next_sibling("p")
    

    一个更简单的方法是使用 nth-of-type

    print(soup.select_one("p:nth-of-type(3)"))
    

    您还应该知道,找到第三个出现的 p 与使用 nth-of-type 实际上确实会在页面中找到第三个 p 标签,如果第一个 p 没有两个兄弟 p em> 标签,那么你的逻辑就会失败。

    要真正使用查找逻辑获得第三个出现的 p,只需使用 find_next

      third_paragraph = soup.find("p").find_next('p').find_next("p")
    

    如果你想要前三个使用 find_all 并将限制设置为 3:

     soup.find_all("p", limit=3)
    

    关于使用你原来的逻辑来获得前两个:

    first_paragraph = soup.find('p')    # or just soup.p
    
    
    
    second, third = first_paragraph.find_next_siblings("p", limit=2)
    

    如果您只想要 x 标签然后只解析 x 标签,请确保您了解找到 第三个​​出现的 &lt;p&gt; 标签 和第一个 p 标签的第二个兄弟之间的区别它们可能不同。

    【讨论】:

    • 谢谢,`third_paragraph = soup.find("p").find_next('p').find_next("p")` 是真正适合我的方法。
    • 别担心,在页面上的任何位置找到第三个 p 和找到某些同级之间存在细微差别。
    • 是的,我猜这是我的主要错误。我有很多东西要学:)
    【解决方案2】:

    .find_next_siblings('p') 返回一个 BeautifulSoup 结果集,类似于 python 中的列表。请尝试以下代码。

    first_paragraph = soup.find('p')
    siblings = first_paragraph.find_next_siblings('p')
    print "second paragraph:", siblings[0]
    print "third paragraph:", siblings[1]
    

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 1970-01-01
      • 2018-02-09
      • 2014-03-16
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 2017-02-17
      • 2012-08-09
      相关资源
      最近更新 更多