使用Scrapy在页面中的链接顺序

时间:2016-08-29 21:25:06

标签: python scrapy

我对给定的域有一个简单的LinkExtractor规则。这样的事情:Rule(LinkExtractor(allow=('domain\.com/.+/\d+', )), callback='parse_page'),

我想要的是什么,我无法弄清楚,知道页面中链接的位置。

例如,如果一个给定的域在页面上有5条符合我规则的链接,我需要从上到下了解它们在HTML中的顺序。

我发现了很多关于提取顺序的问题,但是没有,或者我误解了一些关于链接本身在HTML中的顺序

1 个答案:

答案 0 :(得分:1)

Scrapy使用lxml进行html解析。 LinkExtractor使用root.iter()进行迭代。 This line to be more exact.

Lxml's docs say:

  

元素为此提供树迭代器。它产生元素   按文档顺序,即按照其标记出现的顺序   将树序列化为XML:

所以对于html源:

<root>
  <child>Child 1</child>
  <child>Child 2</child>
  <another>Child 3</another>
</root>

它会产生:

>>> for element in root.iter(tag=etree.Element):
...     print("%s - %s" % (element.tag, element.text))
root - None
child - Child 1
child - Child 2
another - Child 3

您可以使用上面发布的lxml docs链接中提供的示例复制该过程。