首页 > 解决方案 > 使用 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')

标签: pythonbeautifulsoup

解决方案


如果我理解正确,您可能正在寻找这样的东西:

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>

推荐阅读