python - 使用 beautifulsoup 替换表格内容
问题描述
我想使用漂亮的汤来解析一个包含表格数据的 HTML 文档。我正在做一些NLP。
表格单元格可能只有数字或文本很重。所以在做soup.get_text()之前,我希望按照以下条件更改表格数据的内容。
条件:如果单元格有两个以上的单词(我们可以将一个数字视为一个单词),则只保留它,否则将单元格内容更改为空字符串。
<code to change table data based on condition>
soup = BeautifulSoup(html)
text = soup.get_text()
这是我尝试过的东西。
tables = soup.find_all('table')
for table in tables:
table_body = table.find('tbody')
rows = table_body.find_all('tr')
for row in rows:
cols = row.find_all('td')
for ele in cols:
if len(ele.text.split(' ')<3):
ele.text = ''
但是,我们不能设置 ele.text 所以它会抛出一个错误。
这是一个带有表格的简单 HTML 结构
<!DOCTYPE html>
<html>
<head>
<title>HTML Tables</title>
</head>
<body>
<table border = "1">
<tr>
<td><p><span>Row 1, Column 1, This should be kept because it has more than two tokens</span></p></td>
<td><p><span>not kept</span></p></td>
</tr>
<tr>
<td><p><span>Row 2, Column 1, should be kept</span></p></td>
<td><p><span>Row 2, Column 2, should be kept</span></p></td>
</tr>
</table>
</body>
</html>
解决方案
找到元素后,请使用ele.string.replace_with("")
基于您的示例 html
html='''<html>
<head>
<title>HTML Tables</title>
</head>
<body>
<table border = "1">
<tr>
<td><p><span>Row 1, Column 1, This should be kept because it has more than two tokens</span></p></td>
<td><p><span>not kept</span></p></td>
</tr>
<tr>
<td><p><span>Row 2, Column 1, should be kept</span></p></td>
<td><p><span>Row 2, Column 2, should be kept</span></p></td>
</tr>
</table>
</body>
</html>'''
soup=BeautifulSoup(html,'html.parser')
tables = soup.find_all('table')
for table in tables:
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
for ele in cols:
if len(ele.text.split(' '))<3:
ele.string.replace_with("")
print(soup)
输出:
<html>
<head>
<title>HTML Tables</title>
</head>
<body>
<table border="1">
<tr>
<td><p><span>Row 1, Column 1, This should be kept because it has more than two tokens</span></p></td>
<td><p><span></span></p></td>
</tr>
<tr>
<td><p><span>Row 2, Column 1, should be kept</span></p></td>
<td><p><span>Row 2, Column 2, should be kept</span></p></td>
</tr>
</table>
</body>
</html>
推荐阅读
- python - 合并基于行的相似字段 - Python
- python - pytorch中梯度是如何计算的
- python - 我试图制作一个可移动的矩形。当您运行此代码时,它会显示 pygame 窗口,但没有其他任何内容。有任何想法吗?
- marklogic - 关于 MarkLogic 从 9 升级到 10
- java - 我如何在 mac 中查看 java doc?
- java - 使用 Java8 流在 Java 集合中查找给定值的最近对象
- python - print("str", a) 和 print("str" + a) 的区别
- apache-kafka-streams - 序列化程序与 org.apache.avro.util.Utf8 不兼容
- java - Spring boot 无法以 Java 14 启动
- asp.net-mvc - Square API - 在线支付