python中scrapy處理項目數據的實例分析
在我們處理完數據后,習慣把它放在原有的位置,但是這樣也會出現一定的隱患。如果因為新數據的加入或者其他種種原因,當我們再次想要啟用這個文件的時候,小伙伴們就會開始著急卻怎么也翻不出來,似乎也沒有其他更好的搜集辦法,而重新進行數據整理顯然是不現實的。下面我們就一起看看python爬蟲中scrapy處理項目數據的方法吧。
1、拉取項目
$ git clone https://github.com/jonbakerfish/TweetScraper.git$ cd TweetScraper/$ pip install -r requirements.txt #add ’--user’ if you are not root$ scrapy list$ #If the output is ’TweetScraper’, then you are ready to go.
2、數據持久化
通過閱讀文檔,我們發現該項目有三種持久化數據的方式,第一種是保存在文件中,第二種是保存在Mongo中,第三種是保存在MySQL數據庫中。因為我們抓取的數據需要做后期的分析,所以,需要將數據保存在MySQL中。
抓取到的數據默認是以Json格式保存在磁盤 ./Data/tweet/ 中的,所以,需要修改配置文件 TweetScraper/settings.py 。
ITEM_PIPELINES = { # ’TweetScraper.pipelines.SaveToFilePipeline’:100,#’TweetScraper.pipelines.SaveToMongoPipeline’:100, # replace `SaveToFilePipeline` with this to use MongoDB ’TweetScraper.pipelines.SavetoMySQLPipeline’:100, # replace `SaveToFilePipeline` with this to use MySQL}#settings for mysqlMYSQL_SERVER = '18.126.219.16'MYSQL_DB = 'scraper'MYSQL_TABLE = 'tweets' # the table will be created automaticallyMYSQL_USER = 'root' # MySQL user to use (should have INSERT access granted to the Database/TableMYSQL_PWD = 'admin123456' # MySQL user’s password
內容擴展:
scrapy.cfg是項目的配置文件
from scrapy.spider import BaseSpiderclass DmozSpider(BaseSpider):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): filename = response.url.split('/')[-2] open(filename, ’wb’).write(response.body)
到此這篇關于python中scrapy處理項目數據的實例分析的文章就介紹到這了,更多相關python爬蟲中scrapy如何處理項目數據內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: