python - Scrapy 不会选择第一个子元素的子元素,而是选择所有子元素
问题描述
有这个HTML:
<table class="myTable>
<tbody>
<tr>A1</tr>
<tr>A2</tr>
</tbody>
<table>
<table class="myTable>
<tbody>
<tr>A1</tr>
<tr>A2</tr>
</tbody>
<table>
<table class="myTable>
<tbody>
<tr>A1</tr>
<tr>A2</tr>
</tbody>
<table>
我只想提取A1
和A2
一次。所以我有这个选择:
table = response.xpath('.//table[@class="myTable"]')[0]
row = table.xpath("//tr")
但是,在检查时len(row)
我得到 6,而不是 2,即使我已经检查len(table)
并只得到 1(仅限第一个表)。那我该如何选择呢?
解决方案
您需要使用相对XPath:
row = table.xpath(".//tr")
或者您可以使用它来处理页面上的第一个表格:
rows = response.xpath('(//table[@class="myTable"])[1]//tr')
推荐阅读
- node.js - 如何在节点 js 中连接字符串以调用列
- c# - ASP.NET 核心 3.1。*.cshtml 位置未找到
- xpath - 我需要为以下场景编写一个动态 XPath
- excel - Excel 网页查询
- flutter - StatelessWidget 和 ScrollController
- javascript - 如何从预定函数访问 Firestore 中的文档 ID
- java - 从请求正文中的 Java 列表中提取实体
- javascript - 如何重新渲染 .map() 列表
- c# - 来自 ASP.Net MVC 中 ViewModel 的验证 DropDownList 值
- ansible - Ansible Fetch 模块错误 - 由 ssh_config 导致的管道损坏