p::text').extract() 但是 content.css('.text:not(.text .text)>p::text').extract(-6ren">
gpt4 book ai didi

Python Scrapy 获取不到伪类 ":not()"

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:28 24 4
gpt4 key购买 nike

可以写

content.css('.text>p::text').extract()

但是

content.css('.text:not(.text .text)>p::text').extract()

将不起作用。它告诉我:

SelectorSyntaxError: Expected ')', got <S ' ' at 15>

是的,'.text:not(.text .text)>p::text' 中的第 15 个字母是 ' ',但是我如何不使用 ' ' 来表达这个意思?

更新

有嵌套<div class='text'> s,我想提取所有<p>它就在第一个 <div class='text'> 的下方.

例如:

<div class='text comment'>
<strong>abc</strong>
<span>def</span>
<p>xxxxxxxxxxxxx</p>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
<div class='text sub_comment'>
<strong>lst</strong>
<span>lll</span>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
</div>

我想获取前两个文本 <p> .我不能使用 .comment.sub_comment区分它们,因为它们因情况而异,不一定是 comment在外面和sub_comment在内部标记中。

最佳答案

尝试一下怎么样nth-child(1)

所以你的 CSS 应该是:

".text:nth-child(1)>p"

在 Scrapy 中:

In [54]: from scrapy import Selector

In [55]: a
Out[55]: u"<div><div class='text comment'> <strong>abc</strong> <span>def</span> <p>xxxxxxxxxxxxx</p> <p>xxxxxxxxxxxxxxxxxxxxxxxxxxx</p> <div class='text sub_comment'> <strong>lst</strong> <span>lll</span> <p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p> <p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p> </div></div></div>"

In [56]: sel = Selector(text=a)

In [57]: sel.css(".text:nth-child(1)>p::text").extract()
Out[57]: [u'xxxxxxxxxxxxx', u'xxxxxxxxxxxxxxxxxxxxxxxxxxx']

this tutorial here中有nth-child很好的解释和演示。 (向下滚动到第 22 段)。

关于Python Scrapy 获取不到伪类 ":not()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38182972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com