import json
import requests
from mysql_my import mysql_conn
# 因为不能访问, 所以我们加个头试试
headers = {
#'Accept': '*/*',
#'Accept-Encoding': 'gzip, deflate, br',
#'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
#'Connection': 'keep-alive',
'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',
#'Host': 'xueqiu.com',
#'Referer': 'https://xueqiu.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
#'X-Requested-With': 'XMLHttpRequest',
}
# 获取url
url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=-1&count=10&category=111'
#返回状态码
response = requests.get(url, headers=headers)
#获取返回页面,数据格式为字典格式
res_dict = json.loads(response.text)
#获取需要的数据
list_list = res_dict['list']
#创建空字典,为了下面接收数据
data = {}
# 遍历 list_list
for list_item_dict in list_list:
#列表内的一个item, 为字符串
data_str = list_item_dict['data']
#去掉引号,由字符串转化为字典
list_dict = json.loads(data_str)
#将需要的数据由list_dict转移到空字典data中
data['ids']=list_dict['id']
data['title']=list_dict['title']
data['description'] = list_dict['description']
data['target']=list_dict['target']
try:
#将数据存储到mysql数据库中
sql = 'insert into xueqiu(ids,title,description,target) values("{ids}","{title}","{description}","{target}")'.format(**data)
mc = mysql_conn()
mc.execute_modify_mysql(sql)
#发生错误,直接pass
except:
pass
mysql数据库的连接,保存数据
import pymysql
# mysql_conn 主要的功能就是, 将连接数据库的操作变成只连接一次
class mysql_conn(object):
# 魔术方法, 初始化, 构造函数
def __init__(self):
self.db = pymysql.connect(host='127.0.0.1', user='root', password='123456', port=3306, database='py11')
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()