
最近群里有同学说 各个股票APP热门榜单 , 我这里分期介绍下每个平台如何获取热门榜单,提供一些例子。仅供大家参考。
最近股市行情波动,相信一些朋友和我一样,每天打开雪球,最关心的就是那个“热门榜单”。哪些股票在风口上?市场情绪是冷是热?这个榜单无疑是最好的风向标之一。
能不能自己动手,用Python做一个专属的、实时更新的、可交互的热门股票监控面板呢?
答案是:当然可以!今天,我就带大家用Python,从零开始,打造一个功能强大的雪球热股监控面板。过程非常简单,即使是编程新手也能轻松上手。
我们需要三个核心的Python库,它们分别是:
安装它们非常简单,打开你的终端或命令行,输入
pip install streamlit requests pandas
直接用代码去请求雪球的数据,会遇到一个“拦路虎”——反爬虫机制。服务器会识别出你是脚本,而不是真人浏览器,然后无情地拒绝你(返回400 Bad Request错误)。
怎么办?答案是“伪装”。我们需要让我们的代码请求,看起来像一个真实的浏览器行为。这需要两样东西:
雪球API的通行证主要是两个值:u 和 xq_a_token。
如何获取它们?
F12 键,打开“开发者工具”。xueqiu.com 的请求,在它的 “Request Headers” (请求头) 里找到 Cookie 字段。u=... 和 xq_a_token=... 后面的完整值。万事俱备,只欠代码。下面是我们的核心逻辑,我把它分成了三步:
第1步:请求数据
我们写一个函数,用 requests 库,带上我们精心准备的请求头和Cookie,去获取雪球热门榜的JSON数据。
第2步:处理数据
雪球返回的是原始JSON格式,我们需要用 pandas 把它变成一个结构清晰的表格。我们会:
第3步:Streamlit展示
streamlit run xueqiu_hot_stocks.py
import streamlit as st
import requests
import pandas as pd
import time
# --- 1. 页面基本配置 ---
st.set_page_config(
page_title="雪球热门股票榜",
page_icon="📈",
layout="wide",
initial_sidebar_state="expanded"
)
# --- 2. 数据获取函数 (已更新数据路径) ---
@st.cache_data(ttl=60)
def fetch_xueqiu_hot_stocks():
"""
从雪球API获取热门股票列表数据,使用用户Cookie以绕过反爬虫限制。
"""
u_cookie = 'xxxxx'
token_cookie = 'xxxx'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Referer': 'https://xueqiu.com/',
'Connection': 'keep-alive'
}
cookies = {
'u': u_cookie,
'xq_a_token': token_cookie
}
timestamp = int(time.time() * 1000)
url = f"https://stock.xueqiu.com/v5/stock/hot_stock/list.json?page=1&size=100&order=desc&order_by=value&_={timestamp}&type=20&x=0.5"
try:
with requests.Session() as s:
s.headers.update(headers)
s.cookies.update(cookies)
response = s.get(url, timeout=10)
response.raise_for_status()
data = response.json()
if data.get('error_code') != 0 or 'data' not in data or 'items' not in data['data']:
st.error("API返回的数据格式不正确或存在错误。可能是Cookie已失效或API已更新。")
return None
return data['data']['items']
except requests.exceptions.RequestException as e:
st.error(f"网络请求失败: {e}")
st.warning("请检查你的Cookie是否正确且未过期。")
return None
except Exception as e:
st.error(f"数据解析时发生未知错误: {e}")
return None
# --- 3. 主应用逻辑 ---
def main():
st.title("📈 雪球热门股票实时榜单 ")
if st.button("🔄 手动刷新数据"):
st.cache_data.clear()
st.rerun()
stock_data = fetch_xueqiu_hot_stocks()
if stock_data is None:
st.stop()
# --- 4. 数据处理与转换---
df = pd.DataFrame(stock_data)
# 选择并重命名新的列
df = df[[
'name', 'symbol', 'current', 'percent', 'chg',
'exchange', 'value', 'rank_change'
]].rename(columns={
'name': '名称',
'symbol': '代码',
'current': '现价',
'percent': '涨跌幅(%)',
'chg': '涨跌额',
'exchange': '交易所',
'value': '热度值',
'rank_change': '排名变化'
})
# 数据类型转换
df['现价'] = pd.to_numeric(df['现价'], errors='coerce')
df['涨跌幅(%)'] = pd.to_numeric(df['涨跌幅(%)'], errors='coerce')
df['涨跌额'] = pd.to_numeric(df['涨跌额'], errors='coerce')
df['热度值'] = pd.to_numeric(df['热度值'], errors='coerce')
# 排名变化是整数,使用Int64类型可以处理NaN
df['排名变化'] = pd.to_numeric(df['排名变化'], errors='coerce').astype('Int64')
# 添加雪球链接
df['链接'] = df['代码'].apply(lambda code: f"https://xueqiu.com/S/{code}")
st.subheader("📋 热门股票详情")
column_config = {
"名称": st.column_config.TextColumn("名称", width="large"),
"代码": st.column_config.TextColumn("代码", width="small"),
"现价": st.column_config.NumberColumn("现价(元)", format="%.2f", width="small"),
"涨跌幅(%)": st.column_config.NumberColumn("涨跌幅(%)", format="%.2f%%", width="small"),
"涨跌额": st.column_config.NumberColumn("涨跌额(元)", format="%.2f", width="small"),
"交易所": st.column_config.TextColumn("交易所", width="small"),
"热度值": st.column_config.NumberColumn("热度值", format="%.0f", width="medium"),
"排名变化": st.column_config.NumberColumn("排名变化", format="%d", width="small"),
"链接": st.column_config.LinkColumn("雪球链接", display_text="查看详情", width="small")
}
st.dataframe(
df,
column_config=column_config,
hide_index=True,
use_container_width=True
)
if __name__ == "__main__":
main()如果我的分享对你投资有所帮助,不吝啬给个点赞关注呗。