首页 > 数据库 >【Python爬虫】Scrapy框架文件写入方式CSV,MYSQL,MongoDB_爬取新浪彩票双色球

【Python爬虫】Scrapy框架文件写入方式CSV,MYSQL,MongoDB_爬取新浪彩票双色球

时间:2023-12-13 15:44:39浏览次数:37  
标签:Python MongoDB self spider 爬取 item qihao close def

Spider代码

爬取新浪彩票双色球页面数据,只爬取期号、红球、篮球

class Shuangseqiu11Spider(scrapy.Spider):
    name = "shuangseqiu11"
    allowed_domains = ["sina.com.cn"]
    start_urls = ["https://view.lottery.sina.com.cn/lotto/pc_zst/index?lottoType=ssq&actionType=chzs&type=50&dpc=1"]

    def parse(self, response,**kwargs):
        cpdatas = response.xpath("//*[@id='cpdata']/tr")
        for cpdata in cpdatas:
            qihao = cpdata.xpath("./td[1]/text()").extract_first()
            hongse = cpdata.xpath("./td[@class='chartball01' or @class='chartball20']/text()").extract()
            lanse = cpdata.xpath("./td[@class='chartball02']/text()").extract_first()
            if not hongse:
                continue

            dict = {
                "qihao":qihao,
                "hongse":hongse,
                "lanse":lanse
            }
            yield dict

CSV文件写入

在《爬虫框架Scrapy初使用_爬取4399游戏页面数据》中通过写入一条数据打开一次文件,我们希望的是, 能不能打开一个文件, 然后就用这一个文件句柄来完成数据的保存. 答案是可以的. 我们可以在pipeline中创建两个方法, 一个是open_spider(), 另一个是close_spider(). 看名字也能明白其含义:

  • open_spider(), 在爬虫开始的时候执行一次
  • close_spider(), 在爬虫结束的时候执行一次
    整体代码如下:
class ShuangseqiuPipeline:
    def open_spider(self,spider):
        print("开始了")
        self.f = open('data2.csv',mode='a',encoding="UTF-8")
    def close_spider(self,spider):
        print("结束了")
        self.f.close()
    def process_item(self, item, spider):
        self.f.write(f"{item['qihao']},{'_'.join(item['hongse'])},{item['lanse']}\n")
        return item

MYSQL文件写入

在setting配置中添加Mysql数据库信息

setting.py
# MYSQL配置信息
MYSQL_CONFIG = {
   "host": "localhost",
   "port": 3306,
   "user": "root",
   "password": "test123456",
   "database": "spider",
}
#pipeline.py
from caipiao.settings import MYSQL_CONFIG as mysql
import pymysql

class CaipiaoMySQLPipeline:

    def open_spider(self, spider):
        self.conn = pymysql.connect(host=mysql["host"], port=mysql["port"], user=mysql["user"], password=mysql["password"], database=mysql["database"])

    def close_spider(self, spider):
        self.conn.close()

    def process_item(self, item, spider):
        # 写入文件
        try:
            cursor = self.conn.cursor()
            sql = "insert into caipiao(qihao, red, blue) values(%s, %s, %s)"
            red = ",".join(item['red_ball'])
            blue = ",".join(item['blue_ball'])
            cursor.execute(sql, (item['qihao'], red, blue))
            self.conn.commit()
            spider.logger.info(f"保存数据{item}")
        except Exception as e:
            self.conn.rollback()
            spider.logger.error(f"保存数据库失败!", e, f"数据是: {item}")  # 记录错误日志
        return item

MongoDB文件写入

在setting中添加mongodb配置

MONGO_CONFIG = {
   "host": "localhost",
   "port": 27017,
   #'has_user': True,
   #'user': "python_admin",
   #"password": "123456",
   "db": "python"
}
from caipiao.settings import MONGO_CONFIG as mongo
import pymongo

class CaipiaoMongoDBPipeline:
    def open_spider(self, spider):
        client = pymongo.MongoClient(host=mongo['host'],
                                     port=mongo['port'])
        db = client[mongo['db']]
        #if mongo['has_user']:
        #    db.authenticate(mongo['user'], mongo['password'])
        self.client = client  #  你们那里不用这么麻烦. 
        self.collection = db['caipiao']

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        self.collection.insert({"qihao": item['qihao'], 'red': item["red_ball"], 'blue': item['blue_ball']})
        return item

同时存储数据

在setting配置文件中同时添加三个管道

ITEM_PIPELINES = {
    # 三个管道可以共存~
   'caipiao.pipelines.CaipiaoFilePipeline': 300,
   'caipiao.pipelines.CaipiaoMySQLPipeline': 301,
   'caipiao.pipelines.CaipiaoMongoDBPipeline': 302,
}

标签:Python,MongoDB,self,spider,爬取,item,qihao,close,def
From: https://www.cnblogs.com/fuchangjiang/p/17898859.html

相关文章

  • C++堆——heap与二叉树和python
    数据结构栈-->stack队列-->queue树-->tree堆-->heap散列-->hash图-->graph图结构一般包括顶点和边邻接矩阵DAG,DirectedAcyclicGraph即「有向无环图」树树(Tree)是一种非线性的数据结构,由n个节点组成,其中每个节点都有零个或多个子节点。......
  • Python 初学之华为OD机试题:求最大数字
    题目描述给定一个由纯数字组成以宇符串表示的数值,现要求字符串中的每个数字最多只能出现2次,超过的需要进行删除;删除某个重复的数字后,其它数字相对位置保持不变。如"34533”,数字3重复超过2次,需要册除其中一个3,删除第一个3后获得最大数值"4533"。请返回经过删除操作后的最大的数值......
  • pythonDay22
    【序列化与反序列化】(定义) (使用) (案例) (猴子补丁) 【xml模块】(格式) (案例) 【importconfigparser模块】 写的不好,后续修改 【subprocess模块,执行系统命令】 ......
  • 【Python爬虫】Python爬虫入门教程&注意事项
    ​一、引言        随着互联网的快速发展,网络数据已经成为人们获取信息的重要来源。而爬虫技术作为获取网络数据的重要手段,越来越受到人们的关注。在众多编程语言中,Python因其易学易用、库丰富、社区活跃等优势,成为爬虫开发的首选。本文将带你走进Python爬虫的世界,让你......
  • Python——第五章:logging模块
    filename:文件名format:数据的格式化输出。最终在日志文件中的样子时间-名称-级别-模块:错误信息datefmt:时间的格式level:错误的级别权重,当错误的级别权重大于等于leval的时候才会写入文件importlogginglogging.basicConfig(filename='x1.txt',format='%(asc......
  • 【Python小随笔】 Grpc协议的使用
    定义接口//test.protosyntax="proto3";optioncc_generic_services=true;serviceGreeter{//第一个接口rpcOne(OneRequest)returns(OneResponse){}//第二个接口rpcTwo(TwoRequest)returns(TwoResponse){}}//第1个接口请求值messageOn......
  • Python——第五章:shutil模块
    复制文件把dir1的文件a.txt移动到dir2内importshutilshutil.move("dir1/a.txt","dir2")复制两个文件句柄f1=open("dir2/a.txt",mode="rb")#准备读f1f2=open("dir1/b.txt",mode="wb")#准备写f2shutil.copyfileobj(f1,......
  • python N 字形变换 多种解法
    解法一:使用二维数组defconvert(s,numRows):ifnumRows==1ornumRows>=len(s):returnsrows=['']*numRowsindex,step=0,1forcharins:rows[index]+=charifindex==0:......
  • 随机模拟——蒙特卡洛算法的Python实现
    蒙特卡洛方法是一类基于随机抽样的数值计算技术,通过模拟随机事件的概率过程,从而近似计算复杂问题的数学期望或积分。其核心思想是通过大量的随机抽样来逼近问题的解,从而在随机性中获得问题的统计特性。蒙特卡洛方法广泛应用于概率统计、物理学、金融工程、生物学等领域。在蒙特卡......
  • python——小游戏(ball,bird)
      ball #-*-coding:utf-8-*-"""CreatedonWedDec1309:19:382023@author:kabuqinuo"""importsys#导入sys模块importpygame#导入pygame模块pygame.init()#初始化pygamesize=width,height=640,480#设置窗......