python - 如何在 BeautifulSoup 中删除以前的兄弟姐妹
问题描述
我正在尝试从标签顶部和<hr />
标签下方的下一个兄弟姐妹中删除以前的兄弟姐妹</h2>
,问题是我收到此错误AttributeError: 'NavigableString' object has no attribute 'decompose'
我试图解析的 HTML 是这样的
<h1>Heading text</h1>
<p style="text-align: justify;">this and everything untop i want to delete</p>
<hr />
<p style="margin: 0px; font-size: 12px; font-family: Helvetica;"> this and text below i want to keep</p>
<p style="margin: 0px; font-size: 12px; font-family: Helvetica;"> text tex text</p>
<h2>Heading 2</h2>
<p> this and everything below i want to remove</p>
像上面给出的那样提供 html 不会给出删除兄弟姐妹的结果,只会返回 AttributeError。我做错了什么,我该如何解决这个问题?
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
for prev_sibling in soup.find("hr").previous_siblings:
prev_sibling.decompose()
for next_sibling in soup.find("h2").next_siblings:
prev_sibling.decompose()
解决方案
使用find_previous_siblings
() 和find_next_siblings
()
from bs4 import BeautifulSoup
html='''<h1>Heading text</h1>
<p style="text-align: justify;">this and everything untop i want to delete</p>
<hr />
<p style="margin: 0px; font-size: 12px; font-family: Helvetica;"> this and text below i want to keep</p>
<p style="margin: 0px; font-size: 12px; font-family: Helvetica;"> text tex text</p>
<h2>Heading 2</h2>
<p> this and everything below i want to remove</p>'''
soup = BeautifulSoup(html, 'lxml')
for prev_sibling in soup.find("hr").find_previous_siblings():
prev_sibling.decompose()
for next_sibling in soup.find("h2").find_next_siblings():
next_sibling.decompose()
print(soup)
推荐阅读
- database - Laravel - 尝试通过一对多关系获取数据
- java - ArrayList 和 List 声明
- vue.js - 向子组件中的元素添加或删除类
- html - 我对级联流和特异性的理解正确吗?
- laravel - 为什么我的视图没有重定向到控制器?
- react-native - 如何通过更改其不透明度使我的 TouchableOpacity 对 onPress 立即做出反应,以便用户可以轻松地感觉到他们实际上按下了该按钮?
- python - 如何根据值合并两个字典列表
- node.js - 可以在生产 PostgreSQL 连接中将 rejectUnauthorized 设置为 false 吗?
- angular - Angular 8. Ng2table tabledata 指的是一种类型,但在这里用作值
- html - 在导航栏中使用无序列表有什么好处?