python - 在 Scrapy 中使用第 nth-child

标签 python css-selectors scrapy

我正在尝试使用 Python 工具 Scrapy 提取一些 html。

我的选择器如下:

#navigation > nav > div.js-accordion-menu-wrapper > ul li:nth-child(n+5):nth-child(-n+10) > a::attr(href)

出于某种原因,这根本不起作用。具体来说,'nth-child(-n + x) 似乎不起作用。就像 Scrapy 不使用它或允许它一样。

谁能证实这一点?

最佳答案

带有 cssselect 1.0.0 的 Scrapy 1.2.1 似乎按预期工作。

这是一个示例 scrapy shell session :

In [1]: selector = scrapy.Selector(text="""<ul>
   ...:     <li>1</li>
   ...:     <li>2</li>
   ...:     <li>3</li>
   ...:     <li>4</li>
   ...:     <li>5</li>
   ...:     <li>6</li>
   ...:     <li>7</li>
   ...:     <li>8</li>
   ...:     <li>9</li>
   ...:     <li>10</li>
   ...:     <li>11</li>
   ...:     <li>12</li>
   ...: </ul>""")

In [2]: selector.css('ul li:nth-child(n+5)').extract()
Out[2]: 
['<li>5</li>',
 '<li>6</li>',
 '<li>7</li>',
 '<li>8</li>',
 '<li>9</li>',
 '<li>10</li>',
 '<li>11</li>',
 '<li>12</li>']

In [3]: selector.css('ul li:nth-child(n+5):nth-child(-n+10)').extract()
Out[3]: 
['<li>5</li>',
 '<li>6</li>',
 '<li>7</li>',
 '<li>8</li>',
 '<li>9</li>',
 '<li>10</li>']

我正在使用:

$ scrapy version -v
Scrapy    : 1.2.1
lxml      : 3.6.4.0
libxml2   : 2.9.4
Twisted   : 16.5.0
Python    : 3.5.0+ (default, Oct 11 2015, 09:05:38) - [GCC 5.2.1 20151010]
pyOpenSSL : 16.2.0 (OpenSSL 1.0.2g  1 Mar 2016)
Platform  : Linux-4.4.0-47-generic-x86_64-with-Ubuntu-16.04-xenial

$ pip freeze | grep cssselect
cssselect==1.0.0

关于python - 在 Scrapy 中使用第 nth-child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40664576/

相关文章:

python - 如何在热图右侧添加自定义刻度

python - 如何在 Python 中跳过匹配模式的行?

html - 按下按钮的选择器

css - 输入的特异性[类型 ="text"]

html - 如何在列表中使用 CSS 子选择器?

python - 在 scrapy 中使用 Tor 代理

python - Python中双重递归的结果

python - 如何在运行 local-scheduler 时创建 Luigi 依赖关系图

python - 'NoneType' 对象在 scrapy\twisted\openssl 中没有属性 '_app_data'

python - Scrapy:修改响应中的元素和字段