python - 使用 Beautiful Soup 查找第三个出现的 `<p>` 标签

标签 python html beautifulsoup

如标题所示,我试图了解如何找到第三个出现的 <p>一个网站(例如,我使用了以下网站: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'

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

最佳答案

您使用的是 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 与找到你在页面上找到的第一个 p 的第二个兄弟是不同的,使用 nth-of-type 实际上会在页面中找到第三个 p 标签,如果第一个 p 没有两个兄弟 p 标签那么你的逻辑就会失败。

要使用查找逻辑真正获得第三个出现的 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 tags 然后只解析 x 个标签,只要确保你理解找到 第三个出现的 <p> 之间的区别标记 和第一个 p 标记的第二个兄弟标记,因为它们可能不同。

关于python - 使用 Beautiful Soup 查找第三个出现的 `<p>` 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37149955/

相关文章:

python - Django:将变量从 get_context_data() 传递到 post()

python - 使用python读取网络中所有系统的驱动数据

python - PyQt5 应用程序中的故障排除(QDialog -> QMainWindow)

html - 复制未转换的文本时,在页面中将一个字母显示为另一个字母

javascript - 为什么 "103fm"脚本出现在 Drupal 网站上?

javascript - 创建动态 iframe 不会使其全高并剪切页面

python - 漂亮的汤刮刀和 if...else

python - 如何通过input()输入多个字符串

python - Beautifulsoup 跨度 id 标签到 Pandas

python - Beautifulsoup特殊字符解析错误