【发布时间】:2019-04-04 21:25:37
【问题描述】:
我正在使用带有 XPath 库的 python3.6。在桌子里面爬行给了我一个空列表。并且需要爬取到具体的th。
我的 tr 内容是动态生成的。我需要爬到具有特定 th 值的 tr 。示例 在 HTML 代码中,Rank 出现在第二个 tr 中,但它可以出现在 tr 中的任何位置。它没有特定的索引。需要从具有 Rank th 的 tr 中获取 href。
我的html文件:
<tbody>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">
Product Number
</th>
<td class="a-size-base">
B003NR57BY
</td>
</tr>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">
Rank
</th>
<td>
<span>
<span>#3 in <a href="/gp/bestsellers/pc/11036491/ref=pd_zg_hrsr_pc_1_1_last">Computer Mice</a></span>
<br>
</span>
</td>
</tr>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">
Created Date
</th>
<td class="a-size-base">
June 7, 2010
</td>
</tr>
</tbody>
</table>
Python 代码:
listings_details = parser.xpath(XPATH_PRODUCT_DETAILS)
for row in listings_details:
th = row.xpath("./th/text()")
if th[0].strip() == 'Rank':
categories = row.xpath("./td/span/span//text()")
qid_url= row.xpath("./td/span/span//@href")
我希望输出是
Rank: 3,
url : /gp/bestsellers/pc/11036491/ref=pd_zg_hrsr_pc_1_1_last,
category: Computer Mice
【问题讨论】:
-
在 Python 代码中,第一行缺少 XPATH_PRODUCT_DETAILS = "//table[@id='productDetails_detailBullets_sections1']"
标签: python-3.x xpath lxml