|
| 1 | +#!/bin/env python |
| 2 | +# -*- coding:utf-8 -*- |
| 3 | +# _author:kaliarch |
| 4 | + |
| 5 | +import pymysql |
| 6 | +import configparser |
| 7 | +import spider |
| 8 | + |
| 9 | + |
| 10 | +class MysqlOper: |
| 11 | + # initial database information |
| 12 | + def __init__(self, result_list): |
| 13 | + config = configparser.ConfigParser() |
| 14 | + config.read('db.conf') |
| 15 | + self.host = config['mysql']['HOST'] |
| 16 | + self.port = int(config['mysql']['PORT']) |
| 17 | + self.user = config['mysql']['USER'] |
| 18 | + self.passwd = config['mysql']['PASSWD'] |
| 19 | + self.db = config['mysql']['DB'] |
| 20 | + self.table = config['mysql']['TABLE'] |
| 21 | + self.charset = config['mysql']['CHARSET'] |
| 22 | + self.result_list = result_list |
| 23 | + |
| 24 | + def mysql_save(self): |
| 25 | + |
| 26 | + # create db cursor |
| 27 | + try: |
| 28 | + DB = pymysql.connect(self.host, self.user, self.passwd, self.db, port=self.port, charset=self.charset) |
| 29 | + cursor = DB.cursor() |
| 30 | + except Exception as e: |
| 31 | + print("connect dbserver fail,Please see information:") |
| 32 | + print(e) |
| 33 | + exit(1) |
| 34 | + |
| 35 | + # check and create tables |
| 36 | + cursor.execute('show tables in pydb') |
| 37 | + tables = cursor.fetchall() |
| 38 | + flag = True |
| 39 | + for tab in tables: |
| 40 | + if self.table in tab: |
| 41 | + flag = False |
| 42 | + print('%s is exist' % self.table) |
| 43 | + print(flag) |
| 44 | + if flag: |
| 45 | + cursor.execute( |
| 46 | + '''create table pytab (id int unsigned not null primary key auto_increment, protocol varchar(10),content varchar(50))''') |
| 47 | + else: |
| 48 | + return 0 |
| 49 | + |
| 50 | + # write database |
| 51 | + for values in self.result_list: |
| 52 | + for prot, cont in values.items(): |
| 53 | + try: |
| 54 | + cursor.execute("insert into pytab (protocol,content) value (%s,%s);", [prot, cont]) |
| 55 | + except Exception as e: |
| 56 | + print("insert db occer error", e) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + proxyhelper = spider.GetProxyIP(3) |
| 61 | + res_pool = proxyhelper.get_ip() |
| 62 | + proxy_ip = proxyhelper.right_proxies(res_pool) |
| 63 | + dbhelper = MysqlOper(proxy_ip) |
| 64 | + dbhelper.mysql_save() |
0 commit comments