python - 如何使用 xpath 选择 html 最内部的子值
问题描述
我有一个如下的html结构:
<tr>
<td> AAA </td>
</tr>
<tr>
<td><a> BBB </a></td>
</tr>
//more rows like same as above...
如何选择 <td> 标签内的值?我想要一个类似 ['AAA', 'BBB', ...] 的列表
我厌倦了下面的查询。但由于标签存在,它无法提取第二个表格行的值。
//table//td[1]/text()
谁能建议更通用的 xpath 查询来捕获所有 <td> 条目的值?
谢谢
解决方案
我正在使用 BeautifulSoup 解析您的 html,安装 BeautifulSoup 只需这样做: pip install beautifulsoup4
from bs4 import BeautifulSoup
html_string = """
<table>
<thead>
<tr>
<th>Programming Language</th>
<th>Creator</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr>
<td><a> BBB </a></td>
<td>Dennis Ritchie</td>
<td>1972</td>
</tr>
<tr>
<td>Python</td>
<td>Guido Van Rossum</td>
<td>1989</td>
</tr>
<tr>
<td>Ruby</td>
<td>Yukihiro Matsumoto</td>
<td>1995</td>
</tr>
</tbody>
</table>
"""
my_list = []
soup = BeautifulSoup(html_string, "html.parser")
samples = soup.find_all("td")
for row in samples:
print(row.get_text())
my_list.append(row.get_text())
print(my_list)
推荐阅读
- backend - 有没有办法使用 Knex 来拥有一列数组?
- angularjs - 离子选择动态
- sql - 表值参数“不能将参数 @Queues 声明为只读,因为它不是表值参数”
- css - CSS Grid align-items:基线在 Safari 中不起作用
- regex - 多个正则表达式查询(记事本++)
- google-chrome-devtools - HAR 文件 - 从 Chrome 开发工具网络选项卡访问“大小”列条目?
- javascript - 表单提交后如何打开模式
- eclipse - 如何在eclipse中关闭jsp文件的断线
- css - Bootstrap 4 - 带标签的模态标题 - 如何降低标题高度
- java - 具有复合主键的地图上的休眠 HQL 查询