python - 使用 BeautifulSoup 查找特定文本
问题描述
我需要在 HTML 文档中查找文本。该文档是生成的报告,文本不在任何 HTML 标记中。我需要找到文本“测试”。我已经尝试了以下代码行,但没有任何运气。下面是 HTML 文档的示例。另外,如果可能的话。然后,我想在“BILL”之后将与“test”同一行的名称合并/移动到“NAME3”的末尾。右边的名字是动态的,并且一直在变化。左列是静态的,不会改变所以最终的结果是;
<END RESULT>
<html>
<head>
</head>
<body>
<pre>
<font face="courier new" size=-4>
test......... DOUG
NAME2........... HENRY
NAME3... BILL , DOUG
NAME4...... BOB
test......... ALLAN
NAME2........... MICHAEL
NAME3... MITCHELL, ALLAN
NAME4...... TOM
</pre>
</body>
</html>
<SAMPLE CODE>
<html>
<head>
</head>
<body>
<pre>
<font face="courier new" size=-4>
test......... DOUG
NAME2........... HENRY
NAME3... BILL
NAME4...... BOB
test......... ALLAN
NAME2........... MICHAEL
NAME3... MITCHELL
NAME4...... TOM
</pre>
</body>
</html>
result = soup.find(text = "test")
result = soup.find(text = 'test')
result = soup.find_all(text = "test")
result = soup.find_all(text = 'test')
解决方案
如果我理解正确,您可能正在寻找这样的东西:
from bs4 import BeautifulSoup as bs
namepage = """[your sample code above, fixed - font wasn't closed]"""
soup = bs(namepage,'lxml')
result=soup.find('font')
names = result.text.strip()
newnames= ''
for name in names.splitlines():
if "test" in name:
target= name.split('. ')[1]
if "NAME3" in name:
name += ", "+target
newnames+='\n'+name
result.string.replace_with(' '.join([(elem+'\n') for elem in newnames.splitlines()]) )
soup
输出:
<html>
<head>
</head>
<body>
<pre>
<font face="courier new" size="-4">
test......... DOUG
NAME2........... HENRY
NAME3... BILL, DOUG
NAME4...... BOB
test......... ALLAN
NAME2........... MICHAEL
NAME3... MITCHELL, ALLAN
NAME4...... TOM
</font>
</pre>
</body>
</html>
推荐阅读
- java - Servlet API 中的 Servlet 和资源 URL 冲突
- python - 自己制作的游戏。游戏结束后不执行其他分支
- java - 我无法从 Bob 叔叔的书中理解干净架构的部分(MVP)
- file - bat 文件以使用今天的日期时间更改文件夹中文件的日期时间,从文本列表中读取文件名
- ios - CGImage 裁剪没有给出指定的矩形
- xamarin.ios - Xamarin.iOS - 无法在按钮单击时启动视图控制器
- gdb - 在STM32H7上通过SWD/直接将代码加载到RAM
- apache-spark - Spark:使用数据框在 groupBy 内排序
- performance - 在 React Native 中,将所有图像分组到一个对象中对性能不利吗?
- azure-data-factory - 在来自数据工厂中的逻辑应用的成功通知电子邮件中包含经过的时间/持续时间