python爬虫数据去重_python 爬虫 实现增量去重和定时爬取

前言: 在爬虫过程中,我们可能需要重复的爬取同一个网站,为了避免重复的数据存入我们的数据库中 通过实现增量去重 去解决这一问题 本文还针对了那些需要实时更新的网站 增加了一个定时爬取的功能;

解决思路: 1.获取目标url

2.解析网页

3.存入数据库(增量去重)

4.异常处理

5.实时更新(定时爬取)

下面为数据库的配置 mysql_config.py:

import pymysql

def insert_db(db_table, issue, time_str, num_code):

host = '127.0.0.1'

user = 'root'

password = 'root'

port = 3306

db = 'lottery'

data_base = pymysql.connect(host=host, user=user, password=password, port=port, db=db)

cursor = data_base.cursor()

try:

sql = "INSERT INTO %s VALUES ('%s','%s','%s')" % (db_table, issue, time_str, num_code)

cursor.execute(sql)

data_base.commit()

except ValueError as e:

print(e)

data_base.rollback()

finally:

cursor.close()

data_base.close()

def select_db(issue, db_table):

host = '127.0.0.1'

user = 'root'

password = 'root'

port = 3306

db = 'lottery'

data_base = pymysql.connect(host=host, user=user, password=password, port=port, db=db)

cursor = data_base.cursor()

try:

sql = "SELECT '%s' FROM %s " % (issue, db_table)

cursor.execute(sql)

data_base.commit()

except ValueError as e:

print(e)

data_base.rollback()

finally:

return issue

接下来是主要代码 test.py:

# 使用bs4进行网页解析

# 实现了增量去重

# 实现了定时爬取

import datetime

import time

from bs4 import BeautifulSoup

import requests

from mysql_config import insert_db

from mysql_config import select_db

def my_test():

db_table = 'lottery_table'

url = 'http://kj.13322.com/kl10_dkl10_history_dtoday.html'

res = requests.get(url)

content = res.content

soup = BeautifulSoup(content, 'html.parser', from_encoding='utf8')

c_t = soup.select('#trend_table')[0]

trs = c_t.contents[4:]

for tr in trs:

if tr == '\n':

continue

tds = tr.select('td')

issue = tds[1].text

time_str = tds[0].text

num_code = tr.table.text.replace('\n0', ',').replace('\n', ',').strip(',')

print('期号:%s\t时间:%s\t号码:%s' % (str(issue), str(time_str), str(num_code)))

issue_db = select_db(issue, db_table)

try:

if issue_db == issue:

insert_db(db_table, issue_db, time_str, num_code)

print('添加%s到%s成功' % (issue_db, db_table))

except Exception as e:

print('%s 已经存在!' % issue_db)

print(e)

if __name__ == '__main__':

flag = 0

now = datetime.datetime.now()

sched_time = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute, now.second) +\

datetime.timedelta(seconds=3)

while True:

now = datetime.datetime.now()

if sched_time < now:

time.sleep(3)

print(now)

my_test()

flag = 1

else:

if flag == 1:

sched_time = sched_time + datetime.timedelta(minutes=2)

flag = 0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值