python - 使用 python 和 scrapy 删除第一个标签 html

标签 python xpath scrapy

我有一个 HTML:

<div class="abc">
            <div class="xyz">
                <div class="needremove"></div>
                <p>text</p>
                <p>text</p>
                <p>text</p>
                <p>text</p>
            </div>
    </div>

我用过: response.xpath('//div[contains(@class,"abc")]/div[contains(@class,"xyz")]').extract()

结果:

u'['<div class="xyz">
        <div class="needremove"></div>
        <p>text</p>
        <p>text</p>
        <p>text</p>
        <p>text</p>
    </div>']

我想删除<div class="needremove"></div> 。你可以帮我吗?

最佳答案

您可以通过 class="needremove" 获取除 div 之外的所有子标签:

response.xpath('//div[contains(@class, "abc")]/div[contains(@class, "xyz")]/*[local-name() != "div" and not(contains(@class, "needremove"))]').extract()

来自 shell 的演示:

$ scrapy shell index.html
In [1]: response.xpath('//div[contains(@class, "abc")]/div[contains(@class, "xyz")]/*[local-name() != "div" and not(contains(@class, "needremove"))]').extract()
Out[1]: [u'<p>text</p>', u'<p>text</p>', u'<p>text</p>', u'<p>text</p>']

关于python - 使用 python 和 scrapy 删除第一个标签 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30661440/

相关文章:

python - 如何根据单个scrapy.Spider的不同命令设置不同的IP?

python - 在 Python 中,如何禁止类继承?

python - 如何将视频流从python传输到 Electron ?

python - PyQt 菜单栏 Mac OSX 雪豹

python - 如何清除scrapy中的cookies?

python - module._init_() 最多接受 2 个参数(给定 3 个)(scrapy 教程 w/xpath)

python - TensorFlow InvalidArgumentError : Matrix size-compatible: In[0]: [100, 784], In[1] : [500, 10]

python - Scrapy 没有使用 extract_first() 获得干净的文本

xml - 使用 XPath 在命名空间中选择元素

python - 为 html 表提取 lxml xpath