Heim > Fragen und Antworten > Hauptteil
So sieht der HTML-Code aus:
<p class="details"> <span>detail1</span> <span class="number">1</span> <span>detail2</span> <span>detail3</span> </p>
Ich muss Detail2 und Detail3 extrahieren.
Aber mit diesem Code kann ich nur Details1 abrufen.
info = data.find("p", class_ = "details").span.text
Wie extrahiere ich die erforderlichen Elemente?
Vielen Dank im Voraus!
P粉0418569552023-09-16 15:38:11
在你的情况下,选择更具体的元素,即选择所有具有class为number的元素的兄弟元素:
soup.select('span.number ~ span')
from bs4 import BeautifulSoup html='''<p class="details"> <span>detail1</span> <span class="number">1</span> <span>detail2</span> <span>detail3</span> </p>''' soup = BeautifulSoup(html) [t.text for t in soup.select('span.number ~ span')]
['detail2', 'detail3']
P粉0991457102023-09-16 14:52:27
您可以找到所有的 <span>
并进行普通索引:
from bs4 import BeautifulSoup html_doc = """\ <p class="details"> <span>detail1</span> <span class="number">1</span> <span>detail2</span> <span>detail3</span> </p>""" soup = BeautifulSoup(html_doc, "html.parser") spans = soup.find("p", class_="details").find_all("span") for s in spans[-2:]: print(s.text)
输出结果:
detail2 detail3
或者使用 CSS 选择器:
spans = soup.select(".details span:nth-last-of-type(-n+2)") for s in spans: print(s.text)
输出结果:
detail2 detail3