[英]Scrapy CrawlSpider rules with multiple callbacks
我想創建一個實現scrapy CrawlSpider的ExampleSpider。 我的ExampleSpider應該能夠處理僅包含藝術家信息的頁面,僅包含專輯信息的頁面,以及包含專輯和藝術家信息的一些其他頁面。
我能夠處理前兩個場景。 但問題發生在第三種情況。 我正在使用parse_artist(response)
方法來處理藝術家數據,使用parse_album(response)
方法來處理相冊數據。 我的問題是,如果一個頁面同時包含藝術家和專輯數據,我該如何定義我的規則?
還有其他辦法嗎? (一種正確的方式)
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.