爬取雪球網數據儲存到數據庫

import pymysql
import requests
import json
class mysql_conn(object):
    # 魔術方法, 初始化, 構造函數
    def __init__(self):
        self.db = pymysql.connect(host='127.0.0.1', user='root', password='123456', port=3306, database='test')
        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()
 url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=-1&count=10&category=111'
 headers = {
    'Cookie': 'aliyungf_tc=AQAAALoQF3p02gsAUhVFebQ3uBBNZn+H; xq_a_token=584d0cf8d5a5a9809761f2244d8d272bac729ed4; xq_a_token.sig=x0gT9jm6qnwd-ddLu66T3A8KiVA; xq_r_token=98f278457fc4e1e5eb0846e36a7296e642b8138a; xq_r_token.sig=2Uxv_DgYTcCjz7qx4j570JpNHIs; _ga=GA1.2.516718356.1534295265; _gid=GA1.2.1050085592.1534295265; u=301534295266356; device_id=f5c21e143ce8060c74a2de7cbcddf0b8; Hm_lvt_1db88642e346389874251b5a1eded6e3=1534295265,1534295722; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1534295722',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
 }
response = requests.get(url,headers=headers)
# print(response.text)
res_dict = json.loads(response.text)
# print(res_dict)
list_list = res_dict['list']
#print(list_list)
# 遍歷 list_list
for list_item_dict in list_list:
    # list 列表內的一個item, 他是一個dict
    data_str = list_item_dict['data']
    data_dict = json.loads(data_str)
    print(data_dict)
    id = data_dict['id']
    # print(id)
    title = data_dict['title']
    description = data_dict['description']
    target = data_dict['target']
    if __name__=='__main__':
        sql = "insert into xueqiu_test values ('%d','%s','%s','%s')"%(id,title,description,target)
        mc = mysql_conn()
        mc.execute_modify_mysql(sql)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章