可以写
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 段)。
