利用数据库简单去重

对于数据库一秒能查看40多万数据,为什么要提到这些东西 ,因为我们现在就是用查找数据库里面的一个字段来进行对比的,

代码如下:

              sql1 = "SELECT * FROM    表名      WHERE title = '{}';".format(item['title'])(利用title表字段)

虽然数据库查找方式很快,但是以后数据会逐渐增多  我这里又加了,一个判断 ,来减轻对数据库照成的压力

代码如下:

              if item["timestamp"] >= item["today_time"]:  (timestamp这里是每天凌晨时间,today_time这是爬取时间,看是否是今天的),这样就减轻了对数据库查找的压力

 

最后代码如下:

          

import pymysql
class HealthPipeline(object):
    def __init__(self):
        # 连接数据库
        # dbards = dict(
        self.connect = pymysql.connect(
            
            host='******',
            port=3306
            db='*******',
            user='root',
            passwd='******',
            charset='utf8',
            use_unicode=True)
        self.cursor = self.connect.cursor()

    def process_item(self, item, spider):
       
if item["timestamp"] >= item["today_time"]:
            sql1 = "SELECT * FROM sh_news_auto WHERE title = '{}';".format(item['title'])

            # 将数据插进sh_news表
            sql2 = 'insert into sh_news_auto(uuid,type,member_id,channel_id,title,source,content,url,picurl,images,province_id,city_id,area_id,ip,ctime)values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'

            # print('******************************************************************',item['content'])
            try:
                self.cursor.execute(sql1)
                if self.cursor.fetchall():
                    print('数据已存在')
                else:
                    # self.cursor.execute(sql2)
                    self.cursor.execute(sql2, (
                        0, 0, item['member_id'], 3, item['title'], item['source'], item['content'], 'www.baidu.com',
                        'www.baidu.com',
                        '', 0, 0, 0, 1231231, item['time']))
                    print('更新成功')
                self.connect.commit()
            except Exception as e:
                print(e)
                self.connect.rollback()
            # self.cursor.close()
            # close()
    else:
            print('不是当天新闻')

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值