gpt4 book ai didi

python - 具有多个回调的 Scrapy CrawlSpider 规则

转载 作者:行者123 更新时间:2023-11-28 20:22:25 26 4
gpt4 key购买 nike

我正在尝试创建一个实现 scrapy CrawlSpider 的 ExampleSpider。我的 ExampleSpider 应该能够处理仅包含艺术家信息的页面,仅包含专辑信息的页面,以及包含专辑和艺术家信息的其他一些页面。

我能够处理前两个场景。但问题出现在第三种情况下。我正在使用 parse_artist(response) 方法来处理艺术家数据,使用 parse_album(response) 方法来处理专辑数据。我的问题是,如果一个页面同时包含艺术家和专辑数据,我应该如何定义我的规则?

  1. 我应该喜欢下面吗? (相同 url 模式的两个规则)
  2. 我应该多次回调吗? (scrapy支持多次回调吗?)
  3. 还有其他方法吗? (正确的方法)

    class ExampleSpider(CrawlSpider):
    name = 'example'

    start_urls = ['http://www.example.com']

    rules = [
    Rule(SgmlLinkExtractor(allow=[r'same regex_rule']), callback='parse_artist', follow=True),
    Rule(SgmlLinkExtractor(allow=[r'same regex_rule']), callback='parse_album', follow=True),
    # more rules .....
    ]

    def parse_artist(self, response):
    artist_item = ArtistItem()
    try:
    # do the scrape and assign to ArtistItem
    except Exception:
    # ignore for now
    pass
    return artist_item
    pass

    def parse_album(self, response):
    album_item = AlbumItem()
    try:
    # do the scrape and assign to AlbumItem
    except Exception:
    # ignore for now
    pass
    return album_item
    pass
    pass

最佳答案

CrawlSpider 调用 _requests_to_follow() 方法来提取 url 并生成要遵循的请求:

def _requests_to_follow(self, response):
if not isinstance(response, HtmlResponse):
return
seen = set()
for n, rule in enumerate(self._rules):
links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
if links and rule.process_links:
links = rule.process_links(links)
seen = seen.union(links)
for link in links:
r = Request(url=link.url, callback=self._response_downloaded)
r.meta.update(rule=n, link_text=link.text)
yield rule.process_request(r)

如你所见:

  • 变量seen 内存urls 已被处理。
  • 每个url 最多会被一个callback 解析。

你可以定义一个parse_item()来调用parse_artist()parse_album():

rules = [
Rule(SgmlLinkExtractor(allow=[r'same regex_rule']), callback='parse_item', follow=True),
# more rules .....
]

def parse_item(self, response):

yield self.parse_artist(response)
yield self.parse_album(response)

关于python - 具有多个回调的 Scrapy CrawlSpider 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23695716/

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