gpt4 book ai didi

python - 在 CrawlSpider 中以什么顺序评估规则?

转载 作者:太空宇宙 更新时间:2023-11-04 05:09:25 25 4
gpt4 key购买 nike

我对规则在 CrawlSpider 中的评估顺序有疑问。如果我有以下代码:

from scrapy.contrib.spiders.crawl import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
start_urls = ['http://someurlhere.com']
rules = (
Rule(
LinkExtractor(restrict_xpaths=[
"//ul[@class='menu-categories']",
"//ul[@class='menu-subcategories']"]),
callback='first_callback'
),
Rule(
LinkExtractor(allow='/product.php?id=\d+'),
callback='second_callback'
)
)

在这种情况下:

  • 引擎将发送对 start_url 列表中的 'http://someurlhere.com' 的请求,并调用默认的 parse 回调当它得到响应时。
  • 然后在 parse 方法中,根据我们提供给 FIRST LinkExtractor 的 xpath,从上面步骤获得的响应中提取链接。

现在我的问题是从第一个 LinkExtractor 规则中提取的链接,它们是否只是在调度程序中调度而不是立即执行?因此,在安排从第一个 LinkExtractor 中提取的所有链接之后,它将为所有这些链接调用 first_callback 方法,并将响应传递给 first_callback ?

另外,第二个 LinkExtractor 何时被调用?是否第一个 LinkExtractor 得到评估,然后只有第二个 LinkExtractor 运行?

最佳答案

如果我们通过 official documentation .过程很简单。

首先,您的起始 url 被解析,然后每个后续抓取的页面链接将按照提供的规则提取。

现在回答你的问题。

Now my question is the links that are extracted from the FIRST LinkExtractor rule, are they simply scheduled in the scheduler and not followed immediately? So after it schedules all the links which are extracted from the first LinkExtractor then it will call the first_callback method for all of those links with the response passed to that first_callback?

如果回调为 None,则默认为 True,否则默认为 False。这意味着在您的情况下,将不会有后续行动。它从起始 URL 响应中提取的任何链接都是您将在调度程序中拥有的链接,并且在解析所有这些之后您的抓取将结束。

如果你想遵守,打破规则。找到您的内容和资源在哪里。

# Extract links matching 'products' (but not matching 'shampoo')
# and follow links from them (since no callback means follow=True by default).
Rule(LinkExtractor(allow=('products', ), deny=('shampoo', ))),

# Extract links matching 'item' and parse them with the spider's method parse_item
Rule(LinkExtractor(allow=('item', )), callback='parse_item'),

现在来回答你的第二个问题:

Also when is the second LinkExtractor going to be called? Does the first LinkExtractor get evaluated and then only the second LinkExtractor runs?

一个人不依赖于另一个人。 LinkExtractor 对象独立应用正则表达式或字符串匹配。如果他们找到匹配的 URL,他们会继续回传或跟进。

关于python - 在 CrawlSpider 中以什么顺序评估规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417048/

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