from bs4 import BeautifulSoup
import re
html_content = """<div class='ui very padded vertical segment'>
<div class='ui basic clearing segment' style='margin: 0; padding: 1em 0'>
<h4 class='ui header'>
Description
</h4>
<p>Please bring the failure blade to cabin.</p>
</div>
<div class='column'>
<h4 class='ui header'>
Owner Information
</h4>
<div class='ui list'>
<div class='item'>
<i class='grey user icon'></i>
<div class='content'>No Owner Specified</div>
</div>
</div>
</div>"""

work_order_soup = BeautifulSoup(html_content,"html.parser")
find_description = work_order_soup.find(re.compile("^h[1-6]$"), text=re.compile("Description", re.IGNORECASE))

parent_div_description = find_description.find_parent("div")
print(parent_div_description.text)

在没有找到p标记的情况下,我需要从父div获取文本.实际上,我需要go 掉文本中的描述.我已经使用Find_Description找到了描述. 所需解决方案:请将故障Blade 带到机舱内.

推荐答案

从父项中删除<h*>标记,并获得文本:

import re

from bs4 import BeautifulSoup

html_content = """<div class='ui very padded vertical segment'>
<div class='ui basic clearing segment' style='margin: 0; padding: 1em 0'>
<h4 class='ui header'>
Description
</h4>
<p>Please bring the failure blade to cabin.</p>
</div>
<div class='column'>
<h4 class='ui header'>
Owner Information
</h4>
<div class='ui list'>
<div class='item'>
<i class='grey user icon'></i>
<div class='content'>No Owner Specified</div>
</div>
</div>
</div>"""

work_order_soup = BeautifulSoup(html_content, "html.parser")
find_description = work_order_soup.find(
    re.compile("^h[1-6]$"), string=re.compile("Description", re.IGNORECASE)
)

parent = find_description.parent
find_description.extract()

print(parent.get_text(strip=True))

打印:

Please bring the failure blade to cabin.

Python-3.x相关问答推荐

如何匹配字母,数字,短划线,逗号,但不是如果没有数字和字母?

将strid()映射到Pandas DataFrame中的字符串不会更改NaN条目,但仍然声称它们不同?

Pandas 插入的速度太慢了.对于跟踪代码,什么是更快的替代方案?

估计列表中连续对的数量

添加任意数量的 pandas 数据框

需要找到完全匹配并使用正则表达式替换

如何使用 Selenium 和 Python 作为线程来使用事件(Chrome-Developer-Tools)?

为列表列表中的每个列表插入 str 到 index[0] 中. Python

Python从base64转换为二进制

在 Python 3.5 中使用 aiohttp 获取多个 url

将字符串表示与使用整数值的枚举相关联?

python中是否有大于但小于函数?

如何使用pandas python获取数据框中每列的最大长度

如何判断一个字符串是否包含有效的 Python 代码

如何使 Python3 成为 Geany 中的默认 Python

Selenium (Python) - 使用 Chrome 网络驱动程序等待下载过程完成

使用 urllib3 忽略证书验证

Windows 下 Python 3.x 的 OpenCV

如何在 Python 3.2 中退出?

在 Visual Studio Code 中调试 Scrapy 项目