簡體   English   中英

美湯選老二

[英]selecting second child in beautiful soup

假設有:

<div>
    <p>this is some text</p>
    <p>...and this is some other text</p>
</div>

如何從beautifulsoup的第二段中檢索文本?

您可以使用 CSS 選擇器來執行此操作:

>>> from bs4 import BeautifulSoup

>>>  soup = BeautifulSoup("""<div>
.... <p>this is some text</p>
.... <p>...and this is some other text</p>
.... </div>""", "html.parser")

>>>  soup.select('div > p')[1].get_text(strip=True)
     '...and this is some other text'

您可以使用nth-of-type

h = """<div>
    <p>this is some text</p>
    <p>...and this is some other text</p>
</div>"""


soup = BeautifulSoup(h)

print(soup.select_one("div p:nth-of-type(2)").text)
secondp = [div.find('p') for div in soup.find('div')]

In : secondp[1].text

Out : Your text

或者您可以直接使用findChildren -

div_ = soup.find('div').findChildren()
for i, child in enumerate(div_):
    if i == 1:
         print child.text

你可以用西班牙涼菜湯解決這個問題:

from gazpacho import Soup

html = """\
<div>
    <p>this is some text</p>
    <p>...and this is some other text</p>
</div>
"""

soup = Soup(html)
soup.find('p')[1].text

這將輸出:

'...這是一些其他的文字'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM