在寫scrapy的spider類的parse方法的時候,有些鏈接需要提取出來繼續爬取,這里scrapy提供了一些方法可以方便的實現這個功能,總結如下:
假設我們的目標a標簽是target_a
- 方法1:
next_page = target_a.css('::attr(href)').extract_first() if next_page is not None: next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse)
- 方法2
next_page = target_a.css('::attr(href)').extract_first() if next_page is not None: yield response.follow(next_page, callback=self.parse)
- 方法2變種1
next_page = target_a.css('::attr(href)') if next_page is not None: yield response.follow(next_page[0], callback=self.parse)
- 方法2變種2
if target_a is not None: yield response.follow(target_a, callback=self.parse)
解釋
方法1:直接獲取到下一頁的絕對url,yield一個新Request對象
方法2:不用獲取到絕對的url,使用follow方法會自動幫我們實現
方法2變種1:不用獲取提取url字符串,只需要傳入href這個selector
方法2變種2:不用獲取href這個selector,傳遞一個a的selector,follow方法自動會提取href
注意傳入的對象只能是str或selector,不能是SelectorList