xpath - 从没有属性的div中提取文本
问题描述
我想分别使用 BeautifulSoap 和 XPath 从以下 html 中提取内容(此处为内容)。如何做呢。
<div class="paragraph">
<h1>Title here</h1>
Content here
</div>
输出:
Content here
解决方案
有很多方法可以实现这一点。这里是其中的几个。
通过使用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])
推荐阅读
- flutter - 即使不在当前页面中,Flutter redux 也会不断刷新小部件
- c# - 如何投射 CreateDelegate 并分配给 Action
- python - 是否有某种方法可以编写带有两个布尔值的 If 语句?
- python - 如何提高生物信息学脚本的速度?
- vue.js - DOM中存在多个实例时如何选择Vue组件的特定实例
- node.js - Angular Universal 获取域名:“object”类型上不存在属性“req”
- javascript - JavaScript 不会触发 CSS 转换
- python - 一个复选框用 Python 控制 Maya 中的其他复选框
- django - 我尝试创建我的第一个 django 项目(使用 powershell),但由于错误而未能这样做
- php - Joomla php - 如果未加载则加载