【问题标题】:How do I exclude certain elements using xpath?如何使用 xpath 排除某些元素?
【发布时间】: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>

它是&lt;div&gt;s 和&lt;p&gt;s 中的表数据的混合体,其中包含一堆脚本标签。有时&lt;script&gt; 标记在&lt;div&gt;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


【解决方案1】:

使用//*[not(self::script)]可以排除所有带有&lt;script&gt;标签的子节点

from lxml import etree

# you have invalid closing tags which I have fixed on my string
s = '''
<table id='foobar'>
    <tr>
        <td><p>....</p></td>
        <td><div>...</div></td>
    </tr>
    <tr>
        <td><script type='text/javascript'>...</script></td>
        <td><p>.....<br /></p></td>
    </tr>
    <tr>
        <td><div><p>.....</p></div></td>
        <td><script type='text/javascript'>...</script></td>
    </tr>
    <!--repeat for another 250 or so rows-->
</table>
'''

tree = etree.fromstring(s)

for each in tree.xpath("//table[contains(@id, 'foobar')]//*[not(self::script)]"):
    print each.tag

tr
td
p
td
div
tr
td
td
p
br
tr
td
div
p
td

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2021-11-01
    相关资源
    最近更新 更多