简体   繁体   English

美汤选老二

[英]selecting second child in beautiful soup

Let say a have:假设有:

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

How can I retrieve the text from the second paragraph in beautifulsoup?如何从beautifulsoup的第二段中检索文本?

You can use a CSS selector to do this:您可以使用 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'

You can use nth-of-type :您可以使用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

Or you can use the findChildren directly -或者您可以直接使用findChildren -

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

You could solve this with gazpacho :你可以用西班牙凉菜汤解决这个问题:

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

Which would output:这将输出:

'...and this is some other text' '...这是一些其他的文字'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM