zoukankan      html  css  js  c++  java
  • python增量爬虫

    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 == ' ':
    continue
    tds = tr.select('td')
    issue = tds[1].text
    time_str = tds[0].text
    num_code = tr.table.text.replace(' 0', ',').replace(' ', ',').strip(',')
    print('期号:%s 时间:%s 号码:%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

  • 相关阅读:
    ADB命令无法导出文件到物理机上处理办法
    mysql 分页offset过大性能问题解决思路
    0.通用编程基础
    win10去除快捷方式小箭头
    Java经典编程题
    win10家庭版打开组策略
    js常用事件列表
    计算器 输入式子计算结果 (字符串、抛异常)
    题库
    MyEclipse自动补全设置
  • 原文地址:https://www.cnblogs.com/duanlinxiao/p/11997595.html
Copyright © 2011-2022 走看看