欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python中scrapy处理项目数据的实例分析

时间:2021-09-19 07:52:58|栏目:Python代码|点击:

在我们处理完数据后,习惯把它放在原有的位置,但是这样也会出现一定的隐患。如果因为新数据的加入或者其他种种原因,当我们再次想要启用这个文件的时候,小伙伴们就会开始着急却怎么也翻不出来,似乎也没有其他更好的搜集办法,而重新进行数据整理显然是不现实的。下面我们就一起看看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)

上一篇:Python实现完整的事务操作示例

栏    目:Python代码

下一篇:python super()函数的基本使用

本文标题:python中scrapy处理项目数据的实例分析

本文地址:http://www.codeinn.net/misctech/176018.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有