使用 BeautifulSoup 选择第二个孩子

新手上路,请多包涵

假设我有以下 HTML:

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

如何使用 BeautifulSoup 从第二段中检索文本?

原文由 user3885884 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 541
2 个回答

您可以使用 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'

原文由 styvane 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 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)

原文由 Padraic Cunningham 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题