使用 Python 爬虫获取第 N 个 <td> 元素:导入 BeautifulSoup 库解析 HTML 为 BeautifulSoup 对象查找所有 <td> 元素获取第 N 个 <td> 元素(索引从 0 开始)

如何使用 Python 爬虫获取第 N 个 <td>
在 Python 爬虫中,使用 BeautifulSoup 库可以轻松获取 HTML 文档中的元素,包括 <td> 元素。
要获取第 N 个 <td> 元素,请执行以下步骤:
-
导入 BeautifulSoup
立即学习“Python免费学习笔记(深入)”;
<code class="python">from bs4 import BeautifulSoup</code>
-
解析 HTML
<code class="python">soup = BeautifulSoup(html) # 其中 html 是 HTML 文档或字符串</code>
-
查找所有
<td>元素<code class="python">cells = soup.find_all('td')</code> -
获取第 N 个
<td>元素<code class="python">nth_cell = cells[n - 1] # 其中 n 是第 N 个 `<td>` 元素的索引</code>
例如,要获取表格中第一个 <td> 元素:
<code class="python">first_cell = cells[0]</code>
要获取第四个 <td> 元素:
<code class="python">fourth_cell = cells[3]</code>
需要注意的是,cells 列表从 0 开始索引,因此第一个 <td> 元素的索引为 0,以此类推。










