【发布时间】:2014-11-10 06:29:14
【问题描述】:
所以我正在处理一个 Scrapy 项目,我想使用 XPath 捕获以下 HTML:
<table id='foobar'>
<tr>
<td><p>....</td>
<td><div>...</div></td>
</tr>
<tr>
<td><script type='text/javascript'>...</script></td>
<td><p>.....<br></td>
</tr>
<tr>
<td><div><p>.....</div></td>
<td><script type='text/javascript'>...</script></td>
</tr>
<!--repeat for another 250 or so rows-->
</table>
它是<div>s 和<p>s 中的表数据的混合体,其中包含一堆脚本标签。有时<script> 标记在<div>s 内,这使得这有点复杂。基本上我需要的是整个表,而不是脚本标签或其内容。 XPath 最初是:
//table[contains(@id, 'foobar')]
但这并不排除脚本标签,所以我将其更改为
//table[contains(@id, 'foobar')]//script/*[following-sibling::* and preceding-sibling::*]
认为这会起作用,但是。这是否可以在 xpath 中完成,或者我最好只是从表中获取所有内容,迭代内容,并删除其中包含“文本/javascript”的任何内容?
【问题讨论】:
-
由于您使用的是
Scrapy,您可以使用xpath(不包括脚本标签)在表格中准确提取您想要的项目,无需获取所有内容。但如果项目规模较小,那么先做所有事情也不是一个坏主意。
标签: python html xpath web-scraping scrapy