作為創(chuàng)建請求的捷徑,你可以使用response.follow:
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://quotes.toscrape.com/page/1/',
]
def parse(self,response):
for quote in response.css('div.quote'):
yield{
'text':quote.css('span.text::text').extract_first(),
'author':quote.css('span small::text').extract_first(),
'tags':quote.css('div.tags a.tag::text').extract(),
}
next_page = response.css('li.next a::attr(href)').extract_first()
if next_page is not None:
yield response.follow(next_page,callback = self.parse)
與scrapy.Request不同,response.follow支持網(wǎng)頁直接跳轉(zhuǎn),不需要urljoin方法。需要注意的是response.follow只返回請求實例;你還是要生成這個請求的。
你也可以向選擇器傳遞一個response.follow而不是字符串;此選擇器應(yīng)該可提取重要的屬性:
>>>for href in response.css('li.next a::attr(href)'):
yield response.follow(href, callback = self.parse)
對于<a>標簽元素,這里有個簡單方法:response.follow自動使用了它們的href屬性。所以代碼更簡潔:
>>>for a in response.css('li.next a'):
yield response.follow(a,callback = self.parse)
注意:resposne.follow(response.css('li.next a'))是無效值,因為response.css返回的是具有選擇器所有結(jié)果的一個類似列表的對象,并非單一的選擇器。像例子中的一個for循環(huán),也可使用*response.follow(response.css('li.next a')[0])。