這就是HTML的樣子:
<p class="details"> <span>detail1</span> <span class="number">1</span> <span>detail2</span> <span>detail3</span> </p>
我需要提取detail2和detail3。
但是使用這段程式碼,我只能得到detail1。
info = data.find("p", class_ = "details").span.text
我該如何提取所需的項目?
提前感謝!
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