分析
打开 Chrome 的开发者模式,将股票代码一个一个选出来吧。
我们可以将所有的股票代码存放在一个列表中,剩下的就是找一个网站,循环的去将每一只股票的数据取出来咯。
同花顺
想必各位聪明的同学已经发现了, 000001 就是股票代码。
我们接下来只需要拼接这个链接外汇账号密码http://www.kaifx.cn/question/...,就能源源不断的获取到我们想要的数据。
实战
首先,还是先介绍一下本次实战用到的请求库和解析库为: Requests 和 pyquery 。数据存储最后还是落地在 Mysql 。
获取股票代码列表
第一步当然是先构建股票代码列表咯,我们先定义一个方法:
def get_stock_list(stockListURL):
r =requests.get(stockListURL, headers = headers)
doc = PyQuery(r.text)
list = []
# 获取所有 section 中 a 节点,并进行迭代
for i in doc('.stockTable a').items():
try:
href = i.attr.href
list.append(re.findall(r"\d{6}", href)[0])
except:
continue
list = [item.lower() for item in list] # 将爬取信息转换小写
return list
获取详情数据
详情的数据看起来好像是在页面上的,但是,实际上并不在,实际最终获取数据的地方并不是页面,而是一个数据接口。
1
至于是怎么找出来,小编这次就不说,还是希望各位想学爬虫的同学能自己动动手,去寻找一下,多找几次,自然就摸到门路了。
现在数据接口有了,我们先看下返回的数据吧:
showStockDate({"info":{"000001":{"name":"\u5e73\u5b89\u94f6\u884c"}},"data":{"000001":{"10":"16.13","8":"16.14","9":"15.87","13":"78795234.00","19":"1262802470.00","7":"16.12","15":"40225508.00","14":"37528826.00","69":"17.73","70":"14.51","12":"5","17":"945400.00","264648":"0.010","199112":"0.062","1968584":"0.406","2034120":"9.939","1378761":"16.026","526792":"1.675","395720":"-948073.000","461256":"-39.763","3475914":"313014790000.000","1771976":"1.100","6":"16.12","11":""}}})
1
很明显,这个结果并不是标准的 json 数据,但这个是 JSONP 返回的标准格式的数据,这里我们先处理下头尾,将它变成一个标准的 json 数据,再对照这页面的数据进行解析,最后将分析好的值写入数据库中。
def getStockInfo(list, stockInfoURL):
count = 0
for stock in list:
try:
url = stockInfoURL stock
r = requests.get(url, headers=headers)
# 将获取到的数据封装进字典
dict1 = json.loads(r.text[14: int(len(r.text)) - 1])
print(dict1)
# 获取字典中的数据构建写入数据模版
insert_data = {
"code": stock,
"name": dict1['info'][stock]['name'],
"jinkai": dict1['data'][stock]['7'],
"chengjiaoliang": dict1['data'][stock]['13'],
"zhenfu": dict1['data'][stock]['526792'],
"zuigao": dict1['data'][stock]['8'],
"chengjiaoe": dict1['data'][stock]['19'],
"huanshou": dict1['data'][stock]['1968584'],
"zuidi": dict1['data'][stock]['9'],
"zuoshou": dict1['data'][stock]['6'],
"liutongshizhi": dict1['data'][stock]['3475914']
}
cursor.execute(sql_insert, insert_data)
conn.commit()
print(stock, ':写入完成')
except:
print('写入异常')
# 遇到错误继续循环
continue
完整代码
我们将代码稍作封装,完成本次的实战。
import requests
import re
import json
from pyquery import PyQuery
import pymysql
# 数据库连接
def connect():
conn = pymysql.connect(host='localhost',
port=3306,
user='root',
password='password',
database='test',
charset='utf8mb4')
# 获取操作游标
cursor = conn.cursor()
return {"conn": conn, "cursor": cursor}
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
sql_insert = "insert into stock(code, name, jinkai, chengjiaoliang, zhenfu, zuigao, chengjiaoe, huanshou, zuidi, zuoshou, liutongshizhi, create_date) values (%(code)s, %(name)s, %(jinkai)s, %(chengjiaoliang)s, %(zhenfu)s, %(zuigao)s, %(chengjiaoe)s, %(huanshou)s, %(zuidi)s, %(zuoshou)s, %(liutongshizhi)s, now())"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
def get_stock_list(stockListURL):
r =requests.get(stockListURL, headers = headers)
doc = PyQuery(r.text)
list = []
# 获取所有 section 中 a 节点,并进行迭代
for i in doc('.stockTable a').items():
try:
href = i.attr.href
list.append(re.findall(r"\d{6}", href)[0])
except:
continue
list = [item.lower() for item in list] # 将爬取信息转换小写
return list
def getStockInfo(list, stockInfoURL):
count = 0
for stock in list:
try:
url = stockInfoURL stock
r = requests.get(url, headers=headers)
# 将获取到的数据封装进字典
dict1 = json.loads(r.text[14: int(len(r.text)) - 1])
print(dict1)
# 获取字典中的数据构建写入数据模版
insert_data = {
"code": stock,
"name": dict1['info'][stock]['name'],
"jinkai": dict1['data'][stock]['7'],
"chengjiaoliang": dict1['data'][stock]['13'],
"zhenfu": dict1['data'][stock]['526792'],
"zuigao": dict1['data'][stock]['8'],
"chengjiaoe": dict1['data'][stock]['19'],
"huanshou": dict1['data'][stock]['1968584'],
"zuidi": dict1['data'][stock]['9'],
"zuoshou": dict1['data'][stock]['6'],
"liutongshizhi": dict1['data'][stock]['3475914']
}
cursor.execute(sql_insert, insert_data)
conn.commit()
print(stock, ':写入完成')
except:
print('写入异常')
# 遇到错误继续循环
continue
def main():
list = get_stock_list(stock_list_url)
# list = ['601766']
getStockInfo(list, stock_info_url)
if __name__ == '__main__':
main()