學習網站:scrapy入門教程html
1.建立項目:cmd打開scrapy所在位置,輸入命令json
scrapy startproject tutorial
2.定義item:編輯item.py,對您想要採集的數據類型進行定義。例如:dom
import scrapy class DmozItem(scrapy.Item): title = scrapy.Field() link = scrapy.Field() desc = scrapy.Field()
3.編寫爬蟲:在spiders的文件下新建一個domz_spider.py文件,代碼以下:scrapy
import scrapy from tutorial.items import DmozItem class DmozSpider(scrapy.Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): for sel in response.xpath('//ul/li'): item = DmozItem() item['title'] = sel.xpath('a/text()').extract() item['link'] = sel.xpath('a/@href').extract() item['desc'] = sel.xpath('text()').extract() yield item
4.啓動爬蟲:在cmd的命令行轉至spiders的根目錄下,輸入命令ide
scrapy crawl dmoz
5.保存數據:學習
scrapy crawl dmoz -o items.json
或者網站
scrapy crawl dmoz -o items.csv