下面這個例子將會演示如何從 " http://quotes.toscrape.com/ " 中獲取頁面上所有作者(author)的頁面鏈接衷佃,并爬取作者頁面的相應(yīng)信息,然后進入下一頁重復(fù)上訴步驟蹄葱,直到把網(wǎng)站所有作者信息都爬取完成氏义。
# -*- coding: utf-8 -*-
import scrapy
class AuthorSpider(scrapy.Spider):
name = 'author'
start_urls = ['http://quotes.toscrape.com/']
def parse(self, response):
# 獲取頁面上所有作者的連接
for href in response.css('.author + a::attr(href)').extract():
# 獲取到作者連接后,調(diào)用 parse_author 方法來爬取
yield scrapy.Request(response.urljoin(href),
callback=self.parse_author)
# 獲取下一頁連接并處理
next_page = response.css('li.next a::attr(href)').extract_first()
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback=self.parse)
# 爬取作者頁面图云,并提取相應(yīng)的數(shù)據(jù)
def parse_author(self, response):
def extract_with_css(query):
return response.css(query).extract_first().strip()
yield {
'name': extract_with_css('h3.author-title::text'),
'birthdate': extract_with_css('.author-born-date::text'),
'bio': extract_with_css('.author-description::text'),
}
照樣惯悠,我們用以下命令爬取:
scrapy crawl author -o items.json
值得注意的是竣况,即使一個作者的鏈接出現(xiàn)多次克婶,也不會被重復(fù)爬取,因為 Scrapy 默認(rèn)情況下會自動過濾重復(fù)的 url丹泉;相關(guān)的設(shè)定可以通過 settings.py 中的 DUPEFILTER_CLASS
屬性來調(diào)節(jié)情萤。