为了向您展现Scrapy带来了什么,咱们将使用最简单的运行爬虫的方法向您介绍Scrapy Spider的示例。
将下面代码放在文本文件中,将其命名为quotes_spider.py之类的名称,而后使用runspider命令运行程序:scrapy runspider quotes_spider.py -o quotes.jsoncss
import scrapy class QuotesSpider(scrapy.Spider): name = 'quotes' start_urls = [ 'http://quotes.toscrape.com/tag/humor/', ] def parse(self, response): for quote in response.css('div.quote'): yield { 'author': quote.xpath('span/small/text()').get(), 'text': quote.css('span.text::text').get(), } next_page = response.css('li.next a::attr("href")').get() if next_page is not None: yield response.follow(next_page, self.parse)
完成此操做后,您将在quotes.json文件中具备JSON格式的引号列表,其中包含文本和做者,以下所示(此处从新格式化以提升可读性):python
[{ "author": "Jane Austen", "text": "\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d" }, { "author": "Groucho Marx", "text": "\u201cOutside of a dog, a book is man's best friend. Inside of a dog it's too dark to read.\u201d" }, { "author": "Steve Martin", "text": "\u201cA day without sunshine is like, you know, night.\u201d" }, ...]
查看start_urls:http://quotes.toscrape.com/ta...,看看网页的结构。
在head标签中,引入了两个css文件,一个是bootstrap,还有一个是自定义的css样式。在body中一个做为container的div和一个footer。
在整个做为container的div中有两个div和一个h3标签。第一个div做为一个header box。从源码能够看出包含Quotes to Scrape的div和包含Login的div,使用了col-md-x的class样式。json
上面的页面就是下面HTML所展现的,左侧的是指定class是col-md-8的这个div,右侧的是指定class是col-md-4的这个div。bootstrap
这里左侧的每一个条目对应于右侧中指定class为quote的div.
详细看第一条条目的div的HTML源码,由两个span和一个div组成。第二个span中包含了指定了author的class,内容是做者信息。最后一个div中指定了class为tag的连接。
看代码中的xpath和css中的'span/small/text()'和'span.text::text',能够看到起指定的是span标签下的small标签所包含的做者信息,另外一个指定的是有text的class修饰的span中包含的文本内容。scrapy
'author': quote.xpath('span/small/text()').get(), 'text': quote.css('span.text::text').get(),
下面的HTML显示了Top Ten Tags的结构:ide