对于数据库一秒能查看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('不是当天新闻')