在我们处理完数据后,习惯把它放在原有的位置,但是这样也会出现一定的隐患。如果因为新数据的加入或者其他种种原因,当我们再次想要启用这个文件的时候,小伙伴们就会开始着急却怎么也翻不出来,似乎也没有其他更好的搜集办法,而重新进行数据整理显然是不现实的。下面我们就一起看看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 mysql MYSQL_SERVER = \"18.126.219.16\" MYSQL_DB = \"scraper\" MYSQL_TABLE = \"tweets\" # the table will be created automatically MYSQL_USER = \"root\" # MySQL user to use (should have INSERT access granted to the Database/Table MYSQL_PWD = \"admin123456\" # MySQL user\'s password
内容扩展:
scrapy.cfg是项目的配置文件
from scrapy.spider import BaseSpider class 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)
© 版权声明
THE END
暂无评论内容