Python 查找第三个出现的`<;p>;`标签使用美丽的汤
正如标题所示,我试图理解如何找到网站的第三个出现的Python 查找第三个出现的`<;p>;`标签使用美丽的汤,python,html,beautifulsoup,Python,Html,Beautifulsoup,正如标题所示,我试图理解如何找到网站的第三个出现的(例如,我使用了以下网站:) 使用对的答案,我尝试了以下代码 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,
(例如,我使用了以下网站:)
使用对的答案,我尝试了以下代码
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'
回溯(最近一次呼叫最后一次):
文件“page_109.py”,第21行,in
第三段=第二段。查找下一个兄弟姐妹('p')
AttributeError:'ResultSet'对象没有“查找下一个兄弟姐妹”属性
我试图查找错误,但无法找出错误所在。。查找下一个兄弟姐妹('p')
返回一个类似于python中列表的BeautifulSoup结果集。请尝试以下代码
first_paragraph = soup.find('p')
siblings = first_paragraph.find_next_siblings('p')
print "second paragraph:", siblings[0]
print "third paragraph:", siblings[1]
您使用的是兄弟姐妹,即复数,因此您得到的结果集/列表无法调用。请在上查找下一个兄弟姐妹
如果你想要下一段,你可以使用同级而不是同级:
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")
一种更简单的方法是使用第n种类型:
您还应该注意,查找第三个出现的p与查找页面上找到的第一个p的第二个同级并不相同,使用第n个类型实际上会在页面中找到第三个p标记,如果第一个p没有两个同级p标记,那么您的逻辑将失败
要使用find逻辑真正获得第三个出现的p,只需使用find_next:
如果您想要前三个,请使用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个标记,只需确保您了解查找第三个出现的标记和第一个p标记的第二个同级标记之间的区别,因为它们可能不同。谢谢,`third_段落=soup.find(“p”).find_next(“p”).find_next(“p”).find_next(“p”)`是一个真正适合我的。不用担心,在页面的任何地方找到第三个p和找到某些兄弟姐妹之间有细微的区别。是的,我想这是我的主要错误。我有很多东西要学:)
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)