首页 > 解决方案 > 从没有属性的div中提取文本

问题描述

我想分别使用 BeautifulSoap 和 XPath 从以下 html 中提取内容(此处为内容)。如何做呢。

<div class="paragraph">
    <h1>Title here</h1>
    Content here
</div>

输出:

Content here

标签: xpathbeautifulsoup

解决方案


有很多方法可以实现这一点。这里是其中的几个。

通过使用contents

或通过使用next_element

或者

通过使用next_sibling

或者

通过使用stripped_strings

from bs4 import BeautifulSoup
html='''<div class="paragraph">
    <h1>Title here</h1>
    Content here
</div>'''

soup=BeautifulSoup(html,"html.parser")
print(soup.find('div',class_='paragraph').contents[2].strip())
print(soup.find('div',class_='paragraph').find('h1').next_element.next_element.strip())
print(soup.find('div',class_='paragraph').find('h1').next_sibling.strip())
print(list(soup.find('div',class_='paragraph').stripped_strings)[1])

您也可以使用 css 选择器。

html='''<div class="paragraph">
    <h1>Title here</h1>
    Content here
</div>'''

soup=BeautifulSoup(html,"html.parser")
print(soup.select_one('.paragraph').contents[2].strip())
print(soup.select_one('.paragraph >h1').next_element.next_element.strip())
print(soup.select_one('.paragraph >h1').next_sibling.strip())
print(list(soup.select_one('.paragraph').stripped_strings)[1])

推荐阅读