首页 > 解决方案 > 如何使用 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> 条目的值?

谢谢

标签: pythonhtmlxpath

解决方案


我正在使用 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)

推荐阅读