mcp-query-table 0.2.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 伍侃
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,183 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp_query_table
3
+ Version: 0.2.6
4
+ Summary: query table from website, support MCP
5
+ Author-email: wukan <wu-kan@163.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 伍侃
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Keywords: playwright,mcp,table,iwencai,tdx,eastmoney
29
+ Classifier: Development Status :: 4 - Beta
30
+ Classifier: Programming Language :: Python
31
+ Requires-Python: >=3.10
32
+ Description-Content-Type: text/markdown
33
+ License-File: LICENSE
34
+ Requires-Dist: pandas
35
+ Requires-Dist: loguru
36
+ Requires-Dist: playwright
37
+ Requires-Dist: mcp
38
+ Dynamic: license-file
39
+
40
+ # mcp_query_table
41
+
42
+ 基于`playwright`实现的财经网页表格爬虫,支持`Model Context Protocol (MCP) `。目前可查询来源为
43
+
44
+ - [同花顺i问财](http://iwencai.com/)
45
+ - [通达信问小达](https://wenda.tdx.com.cn/)
46
+ - [东方财富条件选股](https://xuangu.eastmoney.com/)
47
+
48
+ 实盘时,如果某网站宕机或改版,可以立即切换到其他网站。(注意:不同网站的表格结构不同,需要提前做适配)
49
+
50
+ ## 安装
51
+
52
+ ```commandline
53
+ pip install -i https://pypi.org/simple --upgrade mcp_query_table
54
+ pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade mcp_query_table
55
+ ```
56
+
57
+ ## 使用
58
+
59
+ ```python
60
+ import asyncio
61
+
62
+ from mcp_query_table import *
63
+
64
+
65
+ async def main() -> None:
66
+ async with BrowserManager(port=9222, browser_path=None, debug=True) as bm:
67
+ # 问财需要保证浏览器宽度>768,防止界面变成适应手机
68
+ page = await bm.get_page()
69
+ df = await query(page, '收益最好的200只ETF', query_type=QueryType.ETF, max_page=1, site=Site.THS)
70
+ print(df.to_markdown())
71
+ df = await query(page, '年初至今收益率前50', query_type=QueryType.Fund, max_page=1, site=Site.TDX)
72
+ print(df.to_csv())
73
+ df = await query(page, '流通市值前10的行业板块', query_type=QueryType.Index, max_page=1, site=Site.TDX)
74
+ print(df.to_csv())
75
+ # TODO 东财翻页要提前登录
76
+ df = await query(page, '今日涨幅前5的概念板块;', query_type=QueryType.Board, max_page=3, site=Site.EastMoney)
77
+ print(df)
78
+ bm.release_page(page)
79
+ print('done')
80
+ await page.wait_for_timeout(2000)
81
+
82
+
83
+ if __name__ == '__main__':
84
+ asyncio.run(main())
85
+
86
+ ```
87
+
88
+ ## 注意事项
89
+
90
+ 1. 浏览器最好是`Chrome`。如一定要使用`Edge`,除了关闭`Edge`所有窗口外,还要在任务管理器关闭`Microsoft Edge`
91
+ 的所有进程,即`taskkill /f /im msedge.exe`
92
+ 2. 浏览器要保证窗口宽度,防止部分网站自动适配成手机版,导致表格查询失败
93
+ 3. 如有网站账号,请提前登录。此工具无自动登录功能
94
+ 4. 不同网站的表格结构不同,同条件返回股票数量也不同。需要查询后做适配
95
+
96
+ ## 工作原理
97
+
98
+ 不同于`requests`,`playwright`是基于浏览器的,模拟用户在浏览器中的操作。
99
+
100
+ 1. 不需要解决登录问题
101
+ 2. 不需要解决请求构造、响应解析
102
+ 3. 可以直接获取表格数据,所见即所得
103
+ 4. 运行速度慢于`requests`,但开发效率高
104
+
105
+ 数据的获取有:
106
+
107
+ 1. 直接解析HTML表格
108
+ 1. 数字文本化了,不利于后期研究
109
+ 2. 适用性最强
110
+ 2. 截获请求,获取返回的`json`数据
111
+ 1. 类似于`requests`,需要做响应解析
112
+ 2. 灵活性差点,网站改版后,需要重新做适配
113
+
114
+ 此项目采用的是模拟点击浏览器来发送请求,使用截获响应并解析的方法来获取数据。
115
+
116
+ 后期会根据不同的网站改版情况,使用更适合的方法。
117
+
118
+ ## MCP支持
119
+
120
+ 确保可以在控制台中执行`python -m mcp_query_table -h`。如果不能,可能要先`pip install mcp_query_table`
121
+
122
+ 在`Cline`中可以配置如下。其中`command`是`python`的绝对路径,`browser_path`是`Chrome`的绝对路径。
123
+
124
+ ### STDIO方式
125
+
126
+ ```json
127
+ {
128
+ "mcpServers": {
129
+ "mcp_query_table": {
130
+ "command": "D:\\Users\\Kan\\miniconda3\\envs\\py312\\python.exe",
131
+ "args": [
132
+ "-m",
133
+ "mcp_query_table",
134
+ "--format",
135
+ "markdown",
136
+ "--browser_path",
137
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
138
+ ]
139
+ }
140
+ }
141
+ }
142
+ ```
143
+
144
+ ### SSE方式
145
+
146
+ 先在控制台中执行如下命令,启动`MCP`服务
147
+
148
+ ```commandline
149
+ python -m mcp_query_table --format markdown --browser_path "C:\Program Files\Google\Chrome\Application\chrome.exe" --transport sse --mcp_port 8000
150
+ ```
151
+
152
+ 然后就可以连接到`MCP`服务了
153
+ http://localhost:8000/sse
154
+
155
+ ## 使用`MCP Inspector`进行调试
156
+
157
+ ```commandline
158
+ npx @modelcontextprotocol/inspector python -m mcp_query_table --format markdown
159
+ ```
160
+
161
+ 打开浏览器并翻页是一个比较耗时的操作,会导致`MCP Inspector`页面超时,可以`http://localhost:5173/?timeout=60000` 表示超时时间为60秒
162
+
163
+ 第一次尝试编写`MCP`项目,可能会有各种问题,欢迎大家交流。
164
+
165
+ ## `MCP`使用技巧
166
+
167
+ 1. 2024年涨幅最大的100只股票按2024年12月31日总市值排名。三个网站的结果都不一样
168
+ - 同花顺:显示了2201只股票。前5个是工商银行、农业银行、中国移动、中国石油、建设银行
169
+ - 通达信:显示了100只股票,前5个是寒武纪、正丹股份,汇金科技、万丰奥威、艾融软件
170
+ - 东方财富:显示了100只股票,前5个是海光信息、寒武纪、光启技术、润泽科技、新易盛
171
+
172
+ 2. 大语言模型对问题拆分能力弱,所以要能合理的提问,保证查询条件不会被改动。以下推荐第2、3种
173
+ - 2024年涨幅最大的100只股票按2024年12月31日总市值排名
174
+ > 大语言模型非常有可能拆分这句,导致一步查询被分成了多步查询
175
+ - 向东方财富查询“2024年涨幅最大的100只股票按2024年12月31日总市值排名”
176
+ > 用引号括起来,避免被拆分
177
+ - 向东方财富板块查询 “去年涨的最差的行业板块”,再查询此板块中去年涨的最好的5只股票
178
+ > 分成两步查询,先查询板块,再查询股票。但最好不要全自动,因为第一步的结果它不理解“今日涨幅”和“区间涨幅”,需要交互修正
179
+
180
+ ## 参考
181
+
182
+ - [Playwright](https://playwright.dev/python/docs/intro)
183
+ - [Selenium webdriver无法附加到edge实例,edge的--remote-debugging-port选项无效](https://blog.csdn.net/qq_30576521/article/details/142370538)
@@ -0,0 +1,144 @@
1
+ # mcp_query_table
2
+
3
+ 基于`playwright`实现的财经网页表格爬虫,支持`Model Context Protocol (MCP) `。目前可查询来源为
4
+
5
+ - [同花顺i问财](http://iwencai.com/)
6
+ - [通达信问小达](https://wenda.tdx.com.cn/)
7
+ - [东方财富条件选股](https://xuangu.eastmoney.com/)
8
+
9
+ 实盘时,如果某网站宕机或改版,可以立即切换到其他网站。(注意:不同网站的表格结构不同,需要提前做适配)
10
+
11
+ ## 安装
12
+
13
+ ```commandline
14
+ pip install -i https://pypi.org/simple --upgrade mcp_query_table
15
+ pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade mcp_query_table
16
+ ```
17
+
18
+ ## 使用
19
+
20
+ ```python
21
+ import asyncio
22
+
23
+ from mcp_query_table import *
24
+
25
+
26
+ async def main() -> None:
27
+ async with BrowserManager(port=9222, browser_path=None, debug=True) as bm:
28
+ # 问财需要保证浏览器宽度>768,防止界面变成适应手机
29
+ page = await bm.get_page()
30
+ df = await query(page, '收益最好的200只ETF', query_type=QueryType.ETF, max_page=1, site=Site.THS)
31
+ print(df.to_markdown())
32
+ df = await query(page, '年初至今收益率前50', query_type=QueryType.Fund, max_page=1, site=Site.TDX)
33
+ print(df.to_csv())
34
+ df = await query(page, '流通市值前10的行业板块', query_type=QueryType.Index, max_page=1, site=Site.TDX)
35
+ print(df.to_csv())
36
+ # TODO 东财翻页要提前登录
37
+ df = await query(page, '今日涨幅前5的概念板块;', query_type=QueryType.Board, max_page=3, site=Site.EastMoney)
38
+ print(df)
39
+ bm.release_page(page)
40
+ print('done')
41
+ await page.wait_for_timeout(2000)
42
+
43
+
44
+ if __name__ == '__main__':
45
+ asyncio.run(main())
46
+
47
+ ```
48
+
49
+ ## 注意事项
50
+
51
+ 1. 浏览器最好是`Chrome`。如一定要使用`Edge`,除了关闭`Edge`所有窗口外,还要在任务管理器关闭`Microsoft Edge`
52
+ 的所有进程,即`taskkill /f /im msedge.exe`
53
+ 2. 浏览器要保证窗口宽度,防止部分网站自动适配成手机版,导致表格查询失败
54
+ 3. 如有网站账号,请提前登录。此工具无自动登录功能
55
+ 4. 不同网站的表格结构不同,同条件返回股票数量也不同。需要查询后做适配
56
+
57
+ ## 工作原理
58
+
59
+ 不同于`requests`,`playwright`是基于浏览器的,模拟用户在浏览器中的操作。
60
+
61
+ 1. 不需要解决登录问题
62
+ 2. 不需要解决请求构造、响应解析
63
+ 3. 可以直接获取表格数据,所见即所得
64
+ 4. 运行速度慢于`requests`,但开发效率高
65
+
66
+ 数据的获取有:
67
+
68
+ 1. 直接解析HTML表格
69
+ 1. 数字文本化了,不利于后期研究
70
+ 2. 适用性最强
71
+ 2. 截获请求,获取返回的`json`数据
72
+ 1. 类似于`requests`,需要做响应解析
73
+ 2. 灵活性差点,网站改版后,需要重新做适配
74
+
75
+ 此项目采用的是模拟点击浏览器来发送请求,使用截获响应并解析的方法来获取数据。
76
+
77
+ 后期会根据不同的网站改版情况,使用更适合的方法。
78
+
79
+ ## MCP支持
80
+
81
+ 确保可以在控制台中执行`python -m mcp_query_table -h`。如果不能,可能要先`pip install mcp_query_table`
82
+
83
+ 在`Cline`中可以配置如下。其中`command`是`python`的绝对路径,`browser_path`是`Chrome`的绝对路径。
84
+
85
+ ### STDIO方式
86
+
87
+ ```json
88
+ {
89
+ "mcpServers": {
90
+ "mcp_query_table": {
91
+ "command": "D:\\Users\\Kan\\miniconda3\\envs\\py312\\python.exe",
92
+ "args": [
93
+ "-m",
94
+ "mcp_query_table",
95
+ "--format",
96
+ "markdown",
97
+ "--browser_path",
98
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
99
+ ]
100
+ }
101
+ }
102
+ }
103
+ ```
104
+
105
+ ### SSE方式
106
+
107
+ 先在控制台中执行如下命令,启动`MCP`服务
108
+
109
+ ```commandline
110
+ python -m mcp_query_table --format markdown --browser_path "C:\Program Files\Google\Chrome\Application\chrome.exe" --transport sse --mcp_port 8000
111
+ ```
112
+
113
+ 然后就可以连接到`MCP`服务了
114
+ http://localhost:8000/sse
115
+
116
+ ## 使用`MCP Inspector`进行调试
117
+
118
+ ```commandline
119
+ npx @modelcontextprotocol/inspector python -m mcp_query_table --format markdown
120
+ ```
121
+
122
+ 打开浏览器并翻页是一个比较耗时的操作,会导致`MCP Inspector`页面超时,可以`http://localhost:5173/?timeout=60000` 表示超时时间为60秒
123
+
124
+ 第一次尝试编写`MCP`项目,可能会有各种问题,欢迎大家交流。
125
+
126
+ ## `MCP`使用技巧
127
+
128
+ 1. 2024年涨幅最大的100只股票按2024年12月31日总市值排名。三个网站的结果都不一样
129
+ - 同花顺:显示了2201只股票。前5个是工商银行、农业银行、中国移动、中国石油、建设银行
130
+ - 通达信:显示了100只股票,前5个是寒武纪、正丹股份,汇金科技、万丰奥威、艾融软件
131
+ - 东方财富:显示了100只股票,前5个是海光信息、寒武纪、光启技术、润泽科技、新易盛
132
+
133
+ 2. 大语言模型对问题拆分能力弱,所以要能合理的提问,保证查询条件不会被改动。以下推荐第2、3种
134
+ - 2024年涨幅最大的100只股票按2024年12月31日总市值排名
135
+ > 大语言模型非常有可能拆分这句,导致一步查询被分成了多步查询
136
+ - 向东方财富查询“2024年涨幅最大的100只股票按2024年12月31日总市值排名”
137
+ > 用引号括起来,避免被拆分
138
+ - 向东方财富板块查询 “去年涨的最差的行业板块”,再查询此板块中去年涨的最好的5只股票
139
+ > 分成两步查询,先查询板块,再查询股票。但最好不要全自动,因为第一步的结果它不理解“今日涨幅”和“区间涨幅”,需要交互修正
140
+
141
+ ## 参考
142
+
143
+ - [Playwright](https://playwright.dev/python/docs/intro)
144
+ - [Selenium webdriver无法附加到edge实例,edge的--remote-debugging-port选项无效](https://blog.csdn.net/qq_30576521/article/details/142370538)
@@ -0,0 +1,4 @@
1
+ from ._version import __version__
2
+
3
+ from .enums import QueryType, Site
4
+ from .tool import BrowserManager, query
@@ -0,0 +1,29 @@
1
+ from mcp_query_table.server import serve
2
+
3
+
4
+ def main():
5
+ import argparse
6
+
7
+ parser = argparse.ArgumentParser(
8
+ description="query table from website",
9
+ )
10
+
11
+ parser.add_argument("--format", type=str, help="输出格式",
12
+ default='markdown', choices=['markdown', 'csv', 'json'])
13
+ parser.add_argument("--cdp_port", type=int, help="浏览器远程调试端口",
14
+ default=9222)
15
+ parser.add_argument("--browser_path", type=str, help="浏览器类型",
16
+ default=r'C:\Program Files\Google\Chrome\Application\chrome.exe')
17
+
18
+ parser.add_argument("--transport", type=str, help="传输类型",
19
+ default='stdio', choices=['stdio', 'sse'])
20
+ parser.add_argument("--mcp_host", type=str, help="MCP服务端地址",
21
+ default='0.0.0.0')
22
+ parser.add_argument("--mcp_port", type=int, help="MCP服务端端口",
23
+ default='8000')
24
+ args = parser.parse_args()
25
+ serve(args.format, args.cdp_port, args.browser_path, args.transport, args.mcp_host, args.mcp_port)
26
+
27
+
28
+ if __name__ == "__main__":
29
+ main()
@@ -0,0 +1 @@
1
+ __version__ = "0.2.6"
@@ -0,0 +1,21 @@
1
+ from enum import Enum
2
+
3
+
4
+ class QueryType(Enum):
5
+ """查询类型"""
6
+ CNStock = 'A股'
7
+ HKStock = '港股'
8
+ USStock = '美股'
9
+ Index = '指数'
10
+ Fund = '基金'
11
+ ETF = 'ETF'
12
+ ConBond = '可转债'
13
+ Board = '板块'
14
+ Info = '资讯'
15
+
16
+
17
+ class Site(Enum):
18
+ """站点"""
19
+ EastMoney = '东方财富' # 东方财富 条件选股
20
+ TDX = '通达信' # 通达信 问小达
21
+ THS = '同花顺' # 同花顺 i问财
@@ -0,0 +1,56 @@
1
+ from typing import Annotated, Optional
2
+
3
+ from loguru import logger
4
+ from mcp.server.fastmcp import FastMCP
5
+ from pydantic import Field
6
+
7
+ from mcp_query_table import QueryType, Site, query as query_table_query
8
+ from mcp_query_table.tool import BrowserManager
9
+
10
+
11
+ class QueryServer:
12
+ def __init__(self, format: str = 'markdown', port: int = 9222, browser_path: Optional[str] = None) -> None:
13
+ self.format: str = format
14
+ self.browser = BrowserManager(port=port, browser_path=browser_path, debug=False)
15
+
16
+ async def query(self, query_input: str, query_type: QueryType, max_page: int, site: Site):
17
+ page = await self.browser.get_page()
18
+ df = await query_table_query(page, query_input, query_type, max_page, site)
19
+ self.browser.release_page(page)
20
+
21
+ if self.format == 'csv':
22
+ return df.to_csv()
23
+ if self.format == 'markdown':
24
+ return df.to_markdown()
25
+ if self.format == 'json':
26
+ return df.to_json(force_ascii=False, indent=2)
27
+
28
+
29
+ # !!!log_level这一句非常重要,否则Cline/MCP Server/Tools工作不正常
30
+ mcp = FastMCP("query_table_mcp", log_level="ERROR")
31
+ qsv = QueryServer()
32
+
33
+
34
+ @mcp.tool(description="查询金融表格数据")
35
+ async def query(
36
+ query_input: Annotated[
37
+ str, Field(description="查询条件。支持复杂查询,如:`2024年涨幅最大的100只股票按市值排名`")],
38
+ query_type: Annotated[QueryType, Field(default=QueryType.CNStock,
39
+ description="查询类型。支持`A股`、`指数`、`基金`、`港股`、`美股`等")],
40
+ max_page: Annotated[int, Field(default=1, ge=1, le=10, description="最大页数。只查第一页即可")],
41
+ site: Annotated[Site, Field(default=Site.THS, description="站点。支持`东方财富`、`通达信`、`同花顺`")]
42
+ ) -> str:
43
+ return await qsv.query(query_input, query_type, max_page, site)
44
+
45
+
46
+ def serve(format, cdp_port, browser_path, transport, mcp_host, mcp_port):
47
+ qsv.format = format
48
+ qsv.port = cdp_port
49
+ qsv.browser_path = browser_path
50
+ logger.info("serve:{},{},{},{}", qsv.format, qsv.port, qsv.browser_path, transport)
51
+ if transport == 'sse':
52
+ logger.info("mcp:{},{}:{}", transport, mcp_host, mcp_port)
53
+
54
+ mcp.settings.host = mcp_host
55
+ mcp.settings.port = mcp_port
56
+ mcp.run(transport=transport)
@@ -0,0 +1,144 @@
1
+ """
2
+ 东方财富 条件选股
3
+ https://xuangu.eastmoney.com/
4
+
5
+ 1. 部分数据中包含中文单位,如万亿等,导致无法转换为数字,如VOLUME
6
+ 2. 东财翻页需要提前手工登录
7
+ 3. 东财翻页是页面已经翻了,然后等数据来更新,懒加载
8
+ """
9
+ import re
10
+
11
+ import pandas as pd
12
+ from loguru import logger
13
+ from playwright.async_api import Page
14
+
15
+ from mcp_query_table.enums import QueryType
16
+
17
+ # 查询结果
18
+ # 'https://np-pick-b.eastmoney.com/api/smart-tag/stock/v3/pw/search-code'
19
+ # 'https://np-pick-b.eastmoney.com/api/smart-tag/fund/v3/pw/search-code'
20
+ # 'https://np-pick-b.eastmoney.com/api/smart-tag/hk/v3/pw/search-code'
21
+ # 'https://np-pick-b.eastmoney.com/api/smart-tag/cb/v3/pw/search-code'
22
+ # 'https://np-pick-b.eastmoney.com/api/smart-tag/etf/v3/pw/search-code'
23
+ # 'https://np-pick-b.eastmoney.com/api/smart-tag/bkc/v3/pw/search-code'
24
+ # 'https://np-tjxg-b.eastmoney.com/api/smart-tag/bkc/v3/pw/search-code'
25
+ _PAGE1_ = 'https://*.eastmoney.com/api/smart-tag/*/v3/pw/search-code'
26
+
27
+ _type_ = {
28
+ QueryType.CNStock: 'stock',
29
+ QueryType.Fund: 'fund',
30
+ QueryType.HKStock: 'hk',
31
+ QueryType.ConBond: 'cb',
32
+ QueryType.ETF: 'etf',
33
+ QueryType.Board: 'bk', # 比较坑,bkc和bkc的区别
34
+ }
35
+
36
+
37
+ def convert_type(type):
38
+ if type == 'Double':
39
+ return float
40
+ if type == 'String':
41
+ return str
42
+ if type == 'Long':
43
+ return int
44
+ if type == 'Boolean':
45
+ return bool
46
+ if type == 'INT': # TODO 好像未出现过
47
+ return int
48
+ return type
49
+
50
+
51
+ class Pagination:
52
+ def __init__(self):
53
+ self.datas = {}
54
+ self.pageNo = 1
55
+ self.pageSize = 100
56
+ self.total = 1024
57
+ self.columns = []
58
+ self.datas = {}
59
+
60
+ def reset(self):
61
+ self.datas = {}
62
+
63
+ def update(self, pageNo, pageSize, total, columns, dataList):
64
+ self.pageNo = pageNo
65
+ self.pageSize = pageSize
66
+ self.total = total
67
+ self.columns = columns
68
+ self.datas[self.pageNo] = dataList
69
+
70
+ def has_next(self, max_page):
71
+ c1 = self.pageNo * self.pageSize < self.total
72
+ c2 = self.pageNo < max_page
73
+ return c1 & c2
74
+
75
+ def current(self):
76
+ return self.pageNo
77
+
78
+ def get_list(self):
79
+ datas = []
80
+ for k, v in self.datas.items():
81
+ datas.extend(v)
82
+ return datas
83
+
84
+ def get_dataframe(self):
85
+ columns = {x['key']: x['title'] for x in self.columns}
86
+ dtypes = {x['key']: convert_type(x['dataType']) for x in self.columns}
87
+
88
+ df = pd.DataFrame(self.get_list())
89
+ for k, v in dtypes.items():
90
+ if k == 'SERIAL':
91
+ df[k] = df[k].astype(int)
92
+ continue
93
+ if isinstance(v, str):
94
+ logger.info("未识别的数据类型 {}:{}", k, v)
95
+ continue
96
+ try:
97
+ df[k] = df[k].astype(v)
98
+ except ValueError:
99
+ logger.info("转换失败 {}:{}", k, v)
100
+
101
+ return df.rename(columns=columns)
102
+
103
+
104
+ P = Pagination()
105
+
106
+
107
+ def search_code(json_data):
108
+ total = json_data['data']['result']['total']
109
+ columns = json_data['data']['result']['columns']
110
+ dataList = json_data['data']['result']['dataList']
111
+ return total, columns, dataList
112
+
113
+
114
+ async def on_response(response):
115
+ post_data_json = response.request.post_data_json
116
+ pageNo = post_data_json['pageNo']
117
+ pageSize = post_data_json['pageSize']
118
+ P.update(pageNo, pageSize, *search_code(await response.json()))
119
+
120
+
121
+ async def query(page: Page,
122
+ q: str = "收盘价>100元",
123
+ type_: QueryType = 'stock',
124
+ max_page: int = 5) -> pd.DataFrame:
125
+ type = _type_.get(type_, None)
126
+ assert type is not None, f"不支持的类型:{type_}"
127
+
128
+ await page.route(re.compile(r'.*\.(?:jpg|jpeg|png|gif|webp)(?:$|\?)'), lambda route: route.abort())
129
+
130
+ P.reset()
131
+ async with page.expect_response(_PAGE1_) as response_info:
132
+ # 这里不用处理输入编码问题
133
+ await page.goto(f"https://xuangu.eastmoney.com/Result?q={q}&type={type}", wait_until="load")
134
+ await on_response(await response_info.value)
135
+
136
+ while P.has_next(max_page):
137
+ logger.info("当前页为:{}, 点击`下一页`", P.current())
138
+
139
+ # 这种写法解决了懒加载问题
140
+ async with page.expect_response(_PAGE1_) as response_info:
141
+ await page.get_by_role("button", name="下一页").click()
142
+ await on_response(await response_info.value)
143
+
144
+ return P.get_dataframe()