雪球网

import requests
import json
import pymysql

class mysql_conn(object):
    # 魔术方法, 初始化, 构造函数
    def __init__(self):
        self.db = pymysql.connect(host='127.0.0.1',user = 'root',password = '123456',port = 3306,database='py11_mysql')
        self.cursor = self.db.cursor()
    # 执行modify(修改)相关的操作
    def execute_modify_mysql(self, sql):
        self.cursor.execute(sql)
        self.db.commit()
    # 魔术方法, 析构化 ,析构函数
    def __del__(self):
        self.cursor.close()
        self.db.close()





def xueqiu(sql):
    lists = {}
    lists['page'] = '-1'
    i = 0
    while i <= sql:
        # 伪装headers
        headers = {
            'Cookie':'aliyungf_tc=AQAAAOOwalcrOAkAufryckXjyKnpJi7J; xq_a_token=584d0cf8d5a5a9809761f2244d8d272bac729ed4; xq_a_token.sig=x0gT9jm6qnwd-ddLu66T3A8KiVA; xq_r_token=98f278457fc4e1e5eb0846e36a7296e642b8138a; xq_r_token.sig=2Uxv_DgYTcCjz7qx4j570JpNHIs; u=401534335935345; device_id=e6cadb56338d7e4620a72bf0a6cd197e',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36',
        }
        # url
        url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id='+lists["page"]+'&count=10&category=105'

        # 提交url和headers
        response = requests.get(url,headers=headers)
        # print(response.text)
        # 转换为字典格式
        res_json = json.loads(response.text)

        # 根据list取到值
        res_list = res_json['list']
        lists['page'] = str(res_json['next_max_id'])

        my = mysql_conn()
        # 遍历 res_list
        for list_item_dict in res_list:
            # list 列表内的一个item, 他是一个dict
            data_str = list_item_dict['data']
            data_dict = json.loads(data_str)
            data = {}
            data['id'] = data_dict['id']
            data['title'] = pymysql.escape_string(data_dict['title'])
            data['description'] = pymysql.escape_string(data_dict['description'])
            data['target'] = pymysql.escape_string(data_dict['target'])
            # print(data)
        #  执行sql语句

            my.execute_modify_mysql('insert into xueqiu(uid,title,description,target) values ("{id}","{title}","{description}","{target}")'.format(**data))
        i += 1

xueqiu(3)

你可能感兴趣的:(作业)