python,scrapy爬虫sql之爬取数据存储到mysql的piplelines.py配置
2017-08-18 13:44
881 查看
# -*- 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 import MySQLdb DBKWARGS={'db':'test','user':'root', 'passwd':'', 'host':'localhost','use_unicode':True, 'charset':'utf8'} class TutorialPipeline(object): def __init__(self): try: self.con = MySQLdb.connect(**DBKWARGS) except Exception,e: print "Connect db error:",e def process_item(self, item, spider): cur = self.con.cursor() sql = "insert into dmoz_book values(%s,%s,%s)" ###数据库名 lis = (''.join(item["title"]),''.join(item["link"]), ''.join(item["desc"])) ###提取内容标题、链接、描述 try: cur.execute(sql,lis) except Exception,e: print "Insert error:",e self.con.rollback() else: self.con.commit() cur.close() return item def __del__(self): try: self.con.close() except Exception,e: print "Close db error",e
当然也可以简写:
import MySQLdb
#这段代码可以写在settings.py文件中
# database connection parameters
#DBKWARGS={'db':'ippool','user':'root', 'passwd':'toor','host':'localhost','use_unicode':True, 'charset':'utf8'}
class CollectipsPipeline(object):
def process_item(self, item, spider):
DBKWARGS = spider.settings.get('DBKWARGS')
con = MySQLdb.connect(**DBKWARGS)
cur = con.cursor()
sql = ("insert into proxy(IP,PORT,TYPE,POSITION,SPEED,LAST_CHECK_TIME) "
"values(%s,%s,%s,%s,%s,%s)")
lis = (item['IP'],item['PORT'],item['TYPE'],item['POSITION'],item['SPEED'],
item['LAST_CHECK_TIME'])
try:
cur.execute(sql,lis)
except Exception,e:
print "Insert error:",e
con.rollback()
else:
con.commit()
cur.close()
con.close()
return item
相关文章推荐
- 数据可视化 三步走(一):数据采集与存储,利用python爬虫框架scrapy爬取网络数据并存储
- Python爬虫系列之----Scrapy(六)settings.py配置文件详解
- 操作 Python爬虫数据存储MySQL【3】爬取信息
- Python爬虫数据存储MySQL【1】连接方式
- Python爬虫数据存储MySQL【2】模拟登录网页
- Python爬虫进阶一之爬虫框架Scrapy安装配置
- 使用python scrapy爬虫框架 爬取科学网自然科学基金数据
- mysql存储过程数据存取特征 contains sql/no sql/reads sql data/modifies sql data的区别
- [python和大数据-1]利用爬虫登录知乎进行BFS搜索抓取用户信息本地mysql分析【PART1】
- 零基础写python爬虫之爬虫框架Scrapy安装配置
- python爬虫之Scrapy 使用代理配置
- Python爬虫教程——进阶一之爬虫框架Scrapy安装配置
- Python爬虫进阶三之Scrapy框架安装配置
- python爬虫Scrapy学习,在windows下安装和配置
- Python爬虫教程——进阶一之爬虫框架Scrapy安装配置
- (WebSite----Asp.Net Configuration----->无法连接到SQL Server数据库------>选择数据存储区---->应用程序当前被配置为使用提供程序:AspNetSqlProvider)解决方案
- 零基础写python爬虫之爬虫框架Scrapy安装配置
- Wiki——Windows下python2.7 爬虫框架Scrapy环境配置
- Python爬虫框架Scrapy实战之抓取户外数据
- Python 爬虫 正则抽取网页数据和Scrapy简单使用