python - 从 beautifulsoup 中提取 HTML 表格单元格文本
问题描述
我想提取基于文本“出生地”的“加拿大”。如何做到这一点beautifulsoup
?
<html>
<table class="table1">
<tbody>
<tr>
<td>Date(s) of Birth Used</td>
<td>May 14, 1942</td>
</tr>
<tr>
<td>Place of Birth</td>
<td>Canada</td>
</tr>
</tbody>
</table>
</html>
解决方案
你应该试试这个动态 td 值。
from bs4 import BeautifulSoup
contents = '''<html>
<table class="table1">
<tbody>
<tr>
<td>Date(s) of Birth Used</td>
<td>May 14, 1942</td>
</tr>
<tr>
<td>Place of Birth</td>
<td>Canada</td>
</tr>
</tbody>
</table>
</html>'''
soup = BeautifulSoup(contents, 'html.parser')
table_div = soup.find(class_ = "table1")
td_val = table_div.findAll('td')
updated_td_val = list(map(str, td_val))
# You can use input() instead of '<td>Place of Birth</td>' to take dynamic input and on basis of that input, it will return you the content of input td and it's next td.
if updated_td_val and '<td>Place of Birth</td>' in updated_td_val:
index_val = updated_td_val.index('<td>Place of Birth</td>')
print(td_val[index_val].get_text())
print(td_val[index_val+1].get_text())
输出 :
Place of Birth
Canada
推荐阅读
- docker - Docker 文件通过不同的镜像持久化
- perl - 这个 Perl 中可能存在什么安全问题?
- python - 从边界框坐标列表创建形状文件
- python - 使用元图张量流运行模型失败
- salesforce - Docusign - 指定的信封要么不存在,要么您无权使用它。- 使用 Gmail 引发的错误
- reactjs - 如何在反应虚拟化表中排序
- vb.net - 如果启动表单从代码中关闭,则启动画面会导致跨线程异常
- wordpress - 需要进行哪些编辑,以便 Jetpack 热门帖子显示所有时间的热门帖子,而不仅仅是过去 2 天?
- javascript - flow-type 用于“A”属性的可能值的动态依赖关系(数组
) 值 'B' ([prop: string]: any) - r - igraph 简化了尝试为边缘着色时