没有属性从div提取文本

时间:2019-11-13 16:55:47

标签: xpath beautifulsoup

我想分别使用BeautifulSoap和XPath从以下html提取内容(此处为Content)。 怎么做。

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

输出:

Content here

1 个答案:

答案 0 :(得分:1)

有很多方法可以实现这一目标。

通过使用contents

或 通过使用next_element

OR

通过使用next_sibling

OR

通过使用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])