scrapy 的文檔請移駕到 http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/install.html
1、准備工作
安裝python 、Spyder 、scrapy 如果想要數據直接入mysql 還需要安裝python的 MySQLdb 依賴包
本人mac操作系統 安裝MySQLdb的時候出現了些小問題 最后是重裝了openssl 才通過的
Spyder 是編寫python的ide
2、新建項目
cd /usr/local/var/www/python
執行 scrapy startproject myblog 則新建了一個名稱為myblog 的項目,執行完成后 你的python文件夾就出現了myblog文件夾了
cnblog_spider.py 是后來我新建的 后綴.pyc 是執行python后的編譯的文件 其他的都是執行創建項目后就自動生成的文件了
3、編寫爬蟲腳本 cnblog_spider.py
分析cnblog的網站 使用scrapy shell http://www.cnblogs.com/threemore/
使用google瀏覽器 找到你想要抓取的數據 話不多說 直接上代碼,我抓取了cnblog文章的標題,鏈接 時間,文章的id,正文內容
# -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from myblog.items import MyblogItem import scrapy import re #SITE_URL = 'http://www.cnblogs.com/threemore/' #抓取在cnblog中的文章 class CnblogSpider(Spider): #抓取名稱 執行命令的時候后面的名稱 scrapy crawl cnblog 中的cnblog 就是在這里定義的 name ='cnblog' allow_domains = ["cnblogs.com"] #定義抓取的網址 start_urls = [ 'http://www.cnblogs.com/threemore/' ] #執行函數 def parse(self,response): sel = Selector(response) self.log("begins % s" % response.url) article_list = sel.css('div.postTitle').xpath('a') #抓取列表里面的內容也地址后循環抓取列表的內容頁面數據 for article in article_list: url = article.xpath('@href').extract()[0] self.log("list article url: % s" % url) #繼續抓取內容頁數據 yield scrapy.Request(url,callback=self.parse_content) #如果有下一頁繼續抓取數據 next_pages = sel.xpath('//*[@id="nav_next_page"]/a/@href') if next_pages : next_page = next_pages.extract()[0] #print next_page self.log("next_page: % s" % next_page) #自己調用自己 類似php 函數的當中的遞歸 yield scrapy.Request(next_page,callback=self.parse) #內容頁抓取 def parse_content(self,response): self.log("detail views: % s" % response.url) #定義好的item 只需要在items 文件中定義抓取過來的數據對應的字段 item = MyblogItem() #xpath 尋找需要在頁面中抓取的數據 item['link'] = response.url #正則匹配出文章在cnblog中的id m = re.search(r"([0-9])+", item['link']) if m: item['aid'] = m.group(0) else: item['aid'] = 0; item['title'] = response.xpath('//*[@id="cb_post_title_url"]/text()').extract()[0] item['content'] = response.xpath('//*[@id="cnblogs_post_body"]').extract()[0] item['date'] = response.xpath('//*[@id="post-date"]').extract() #print item['content'] yield item
4、數據入庫
編寫管道程序pipelines.py,管道就是存儲數據使用的 爬蟲文件最后yield 的item 會將數據給到pipelines.py 這個文件
為了測試和正式環境的方便 我就配置了兩份mysql的登陸信息
每次執行前 都將即將入庫的數據表給清空了一次 防止重復采集 ,直接看代碼
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html #需要在setting.py文件中設置ITEM_PIPELINES 將前面的注釋打開配置成當前的文件即可 #當前的管道就是這么配置 'myblog.pipelines.MyblogPipeline': 300, import MySQLdb,datetime DEBUG = True #定義測試環境和正式環境中的mysql if DEBUG: dbuser = 'root' dbpass = 'root' dbname = 'test' dbhost = '127.0.0.1' dbport = '3306' else: dbuser = 'root' dbpass = 'root' dbname = 'test' dbhost = '127.0.0.1' dbport = '3306' class MyblogPipeline(object): #初始化 鏈接數據庫 def __init__(self): self.conn = MySQLdb.connect(user=dbuser, passwd=dbpass, db=dbname, host=dbhost, charset="utf8", use_unicode=True) self.cursor = self.conn.cursor() self.cursor.execute('truncate table test_cnbog') self.conn.commit() #執行sql語句 def process_item(self, item, spider): try: self.cursor.execute("""INSERT INTO test_cnbog (title, link, aid,content,date) VALUES (%s,%s,%s,%s,%s)""", ( item['title'].encode('utf-8'), item['link'].encode('utf-8'), item['aid'], item['content'].encode('utf-8'), datetime.datetime.now(), ) ) self.conn.commit() except MySQLdb.Error, e: print u'Error %d: $s' % (e.args[0],e.args[1]) return item
5、配置setting.py
開啟入庫的配置
找到 ITEM_PIPELINES 將前面的注釋去掉 看到代碼上面的注釋的鏈接了么 直接訪問看下是干啥的就行了 官方網站上看實例好像是將數據寫入到monge里面去了
本人對monge 不熟悉 直接放到mysql去了 大致意思就是說pipelines.py 這個文件就是講你采集的數據存放在什么地方
# Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'myblog.pipelines.MyblogPipeline': 300, }
6、執行采集
在項目的文件夾下面執行 :scrapy crawl myblog
特意將crawl 拿百度翻譯看了下 啥意思 原來就是“爬行”
最后展示下采集回來的數據
15條沒有采集到數據 aid 程序就是拿正則隨便處理了下