Jarvis-Brain 0.1.10.0__tar.gz → 0.1.11.10__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Jarvis_Brain
3
- Version: 0.1.10.0
3
+ Version: 0.1.11.10
4
4
  Summary: Jarvis brain mcp
5
5
  Requires-Python: >=3.10
6
6
  Requires-Dist: beautifulsoup4
@@ -8,3 +8,4 @@ Requires-Dist: curl-cffi
8
8
  Requires-Dist: drissionpage
9
9
  Requires-Dist: fastmcp
10
10
  Requires-Dist: minify-html
11
+ Requires-Dist: pillow
@@ -4,13 +4,15 @@
4
4
  import hashlib
5
5
  import json
6
6
  import os
7
+ import time
7
8
  from typing import Any
8
9
 
10
+ import DrissionPage
9
11
  from fastmcp import FastMCP
10
12
 
11
13
  from tools.browser_manager import BrowserManager
12
14
  from tools.tools import compress_html, requests_html, dp_headless_html, assert_waf_cookie, dp_mcp_message_pack, \
13
- compress_html_js
15
+ compress_html_js, compress_image_bytes
14
16
  from tools.browser_proxy import DPProxyClient, DPProxyClientManager
15
17
 
16
18
  html_source_code_local_save_path = os.path.join(os.getcwd(), "html-source-code")
@@ -161,13 +163,13 @@ def register_check_selector(mcp: FastMCP, browser_manager):
161
163
  attr_output = json.dumps(ele_attr_list, ensure_ascii=False)
162
164
  # 对attr_output逐个截断,截断的长度为:一轮最大token除以元素个数+3个点+两个引号和逗号
163
165
  return dp_mcp_message_pack(
164
- f"已完成tab页:【{tab_id}】对:【{css_selector}】的检查",
166
+ f"已完成tab页:【{tab_id}】对:【{css_selector}】的检查,当前选中了 {len(target_eles)} 个元素",
165
167
  tab_id=tab_id,
166
168
  selector=css_selector,
167
169
  selector_ele_exist=exist_flag,
168
170
  page_size=page_size,
169
171
  offset=offset,
170
- attr_output=attr_output
172
+ attr_output=attr_output,
171
173
  )
172
174
 
173
175
 
@@ -235,27 +237,33 @@ def register_assert_waf(mcp: FastMCP, browser_manager):
235
237
 
236
238
 
237
239
  def register_click_action(mcp: FastMCP, browser_manager):
238
- @mcp.tool(name="click_action", description="尝试点击tab页中的元素,返回元素是否可以被点击,以及是否点击成功。")
239
- async def click_action(browser_port: int, tab_id: str, css_selector: str) -> dict[str, Any]:
240
+ @mcp.tool(name="click_action",
241
+ description="尝试点击tab页中的元素,返回元素是否可以被点击,以及是否点击成功。"
242
+ "其中target_element_index默认为0,当传入的Selector可以定位到多个元素时,需要传入target_element_index指定具体点击目标 ")
243
+ async def click_action(browser_port: int, tab_id: str, css_selector: str, target_element_index: int = 0) -> dict[
244
+ str, Any]:
240
245
  _browser = browser_manager.get_browser(browser_port)
241
246
  target_tab = _browser.get_tab(tab_id)
242
247
  css_selector = css_selector
243
248
  if "css:" not in css_selector:
244
249
  css_selector = "css:" + css_selector
245
250
  target_eles = target_tab.eles(css_selector)
246
- click_success = False
247
- element_clickable = False
248
- if len(target_eles) == 1:
249
- target_element = target_eles[0]
250
- element_clickable = target_element.states.is_clickable
251
- try:
252
- target_element.click()
253
- click_success = True
254
- except Exception as e:
255
- click_success = False
256
- message = f"tab页:【{tab_id}】点击【{css_selector}】 {'成功' if click_success else '失败'} 了"
251
+ # click_success = False
252
+ # element_clickable = False
253
+ # if len(target_eles) == 1:
254
+ target_element = target_eles[target_element_index]
255
+ element_clickable = target_element.states.is_clickable
256
+ try:
257
+ target_element.click()
258
+ click_success = True
259
+ except Exception as e:
260
+ click_success = False
261
+ if target_element_index > 0:
262
+ message = f"tab页:【{tab_id}】点击【{css_selector}】【index={target_element_index}】的元素 {'成功' if click_success else '失败'} 了"
257
263
  else:
258
- message = f"tab页:【{tab_id}】传入的css_selector找到了{len(target_eles)}个元素,请确保传入的css_selector可以找到唯一的一个元素"
264
+ message = f"tab页:【{tab_id}】点击【{css_selector}】 {'成功' if click_success else '失败'}"
265
+ # else:
266
+ # message = f"tab页:【{tab_id}】传入的css_selector找到了{len(target_eles)}个元素,请确保传入的css_selector可以找到唯一的一个元素"
259
267
  return dp_mcp_message_pack(
260
268
  message=message,
261
269
  browser_port=browser_port,
@@ -304,3 +312,27 @@ def register_scroll_action(mcp: FastMCP, browser_manager):
304
312
  browser_port=browser_port,
305
313
  tab_id=tab_id,
306
314
  )
315
+
316
+
317
+ def register_get_screenshot(mcp: FastMCP, browser_manager):
318
+ @mcp.tool(name="get_tab_screenshot",
319
+ description="尝试对传入tab页进行截图,并将截图压缩为1M大小png图片,会返回截图保存路径")
320
+ async def get_tab_screenshot(browser_port: int, tab_id: str) -> dict[str, Any]:
321
+ _browser = browser_manager.get_browser(browser_port)
322
+ target_tab = _browser.get_tab(tab_id)
323
+ target_tab.wait.doc_loaded()
324
+ if not os.path.exists(html_source_code_local_save_path):
325
+ os.makedirs(html_source_code_local_save_path)
326
+ timestamp = int(time.time() * 1000)
327
+ # time.sleep(1)
328
+ origin_png = target_tab.get_screenshot(as_bytes="jpg", full_page=True)
329
+ compress_png = compress_image_bytes(origin_png, 0.5)
330
+ image_path = os.path.join(html_source_code_local_save_path, f"{browser_port}_{tab_id}_{timestamp}.jpg")
331
+ with open(image_path, "wb") as f:
332
+ f.write(compress_png)
333
+ return dp_mcp_message_pack(
334
+ message=f"已完成对browser_port={browser_port},tab_id={tab_id}的截屏",
335
+ browser_port=browser_port,
336
+ tab_id=tab_id,
337
+ screenshot_path=image_path
338
+ )
@@ -20,6 +20,7 @@ if "TeamNode-Dp" in enabled_modules:
20
20
  register_get_html(mcp, browser_manager)
21
21
  register_check_selector(mcp, browser_manager)
22
22
  register_pop_first_packet(mcp, browser_manager, client_manager)
23
+ register_get_screenshot(mcp, browser_manager)
23
24
  # 页面交互
24
25
  register_click_action(mcp, browser_manager)
25
26
  register_scroll_action(mcp, browser_manager)
@@ -29,7 +30,7 @@ if "JarvisNode" in enabled_modules:
29
30
 
30
31
 
31
32
  def main():
32
- mcp.run(transport="stdio",show_banner=False)
33
+ mcp.run(transport="stdio", show_banner=False)
33
34
 
34
35
 
35
36
  if __name__ == '__main__':
@@ -1,13 +1,14 @@
1
1
  [project]
2
2
  name = "Jarvis_Brain" # 别人下载时用的名字,必须在 PyPI 上唯一
3
- version = "0.1.10.0"
3
+ version = "0.1.11.10"
4
4
  description = "Jarvis brain mcp"
5
5
  dependencies = [
6
6
  "fastmcp",
7
7
  "DrissionPage",
8
8
  "minify-html",
9
9
  "beautifulsoup4",
10
- "curl_cffi"
10
+ "curl_cffi",
11
+ "pillow"
11
12
  ]
12
13
  requires-python = ">=3.10"
13
14
 
@@ -140,7 +140,10 @@ def check_data_packet(packet: DataPacket, client: DPProxyClient):
140
140
  data = packet.request.postData
141
141
  domain = urlparse(url).netloc
142
142
  body = packet.response.body
143
- body_str = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
143
+ if isinstance(body, dict):
144
+ body_str = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
145
+ else:
146
+ body_str = str(body)
144
147
  body_str_list = [body_str[i:i + one_turn_max_token] for i in range(0, len(body_str), one_turn_max_token)]
145
148
  body_completed = True
146
149
  packet_filter = client.packet_filter
@@ -155,30 +158,20 @@ def check_data_packet(packet: DataPacket, client: DPProxyClient):
155
158
  continue
156
159
  if (index + 1) != len(body_str_list):
157
160
  body_completed = False
161
+ try:
162
+ response_headers = packet.response.headers
163
+ except TypeError:
164
+ response_headers = {}
158
165
  temp_dict = {
159
166
  "url": url,
160
167
  "body_completed": body_completed,
161
168
  "method": method,
162
169
  "request_data": data,
163
170
  "request_headers": dict(packet.request.headers),
164
- "response_headers": dict(packet.response.headers),
171
+ "response_headers": dict(response_headers),
165
172
  "response_body_segment": body_str.replace("\\", ""),
166
173
  }
167
174
  client.packet_queue.append(temp_dict)
168
175
 
169
176
 
170
177
  client_manager = DPProxyClientManager()
171
-
172
- # if __name__ == '__main__':
173
- # co = ChromiumOptions().set_user_agent(
174
- # "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Mobile Safari/537.36")
175
- # tab = ChromiumPage(co).latest_tab
176
- # client = DPProxyClient(tab, self_kill=False)
177
- # # client = CaptchaClient(tab, self_kill=True)
178
- # tab = client.get_driver(True)
179
- # url = "https://api.toutiaoapi.com/feoffline/hotspot_and_local/html/hot_list/index.html?client_extra_params=%7B%22custom_log_pb%22%3A%22%7B%5C%22style_id%5C%22%3A%5C%2240030%5C%22%2C%5C%22entrance_hotspot%5C%22%3A%5C%22search%5C%22%2C%5C%22location%5C%22%3A%5C%22hot_board%5C%22%2C%5C%22category_name%5C%22%3A%5C%22hotboard_light%5C%22%7D%22%7D&count=50&log_pb=%7B%22style_id%22%3A%2240030%22%2C%22entrance_hotspot%22%3A%22search%22%2C%22location%22%3A%22hot_board%22%2C%22category_name%22%3A%22hotboard_light%22%7D&only_hot_list=1&tab_name=stream&enter_keyword=%23%E7%BE%8E%E5%9B%BD%E9%80%80%E5%87%BA66%E4%B8%AA%E5%9B%BD%E9%99%85%E7%BB%84%E7%BB%87%23"
180
- # tab.get(url)
181
- # for _ in range(5056):
182
- # new_packet = client.pop_first_packet()
183
- # print(new_packet, "23")
184
- # time.sleep(1)
@@ -0,0 +1,278 @@
1
+ import time
2
+ import random
3
+ import os
4
+ import minify_html
5
+ from DrissionPage import ChromiumPage, ChromiumOptions
6
+ from bs4 import BeautifulSoup
7
+ from curl_cffi import requests
8
+ from lxml import html, etree
9
+ import base64
10
+ from PIL import Image
11
+ import io
12
+
13
+ compress_html_js = """
14
+ function getSimplifiedDOM(node) {
15
+ // 1. 处理文本节点
16
+ if (node.nodeType === Node.TEXT_NODE) {
17
+ const text = node.textContent.trim();
18
+ return text ? text.slice(0, 100) + (text.length > 100 ? '...' : '') : null;
19
+ }
20
+
21
+ // 2. 过滤无用标签
22
+ const ignoreTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'IFRAME', 'SVG', 'LINK', 'META'];
23
+ if (ignoreTags.includes(node.tagName)) return null;
24
+ if (node.nodeType !== Node.ELEMENT_NODE) return null;
25
+
26
+ // 3. 过滤不可见元素
27
+ // 【注意】这里声明了第一次 style
28
+ const style = window.getComputedStyle(node);
29
+
30
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return null;
31
+
32
+ // 过滤宽高太小的元素(往往是埋点空像素)
33
+ const rect = node.getBoundingClientRect();
34
+
35
+ // 【修复点】删除了这里重复的 const style = ... 代码
36
+ // 直接使用上面已经定义好的 style 变量即可
37
+
38
+ // 如果宽高为0,但溢出可见,说明可能有定位的子元素显示在外面
39
+ if ((rect.width === 0 || rect.height === 0) && style.overflow !== 'visible') return null;
40
+
41
+ // --- 开始构建标签字符串 ---
42
+ const tagName = node.tagName.toLowerCase();
43
+ let tagStr = tagName;
44
+
45
+ // A. 基础标识符 (ID 和 Class)
46
+ if (node.id) tagStr += `#${node.id}`;
47
+ if (node.className && typeof node.className === 'string') {
48
+ const classes = node.className.trim().split(/\s+/);
49
+ if (classes.length > 0) tagStr += `.${classes.join('.')}`;
50
+ }
51
+
52
+ // B. 关键属性白名单
53
+ const props = [];
54
+
55
+ // 通用重要属性
56
+ if (node.getAttribute('role')) props.push(`role="${node.getAttribute('role')}"`);
57
+ if (node.getAttribute('aria-label')) props.push(`aria-label="${node.getAttribute('aria-label')}"`);
58
+ if (node.getAttribute('title')) props.push(`title="${node.getAttribute('title')}"`);
59
+ // 建议增加这个,很多弹窗用这个属性
60
+ if (node.getAttribute('aria-modal')) props.push(`aria-modal="${node.getAttribute('aria-modal')}"`);
61
+
62
+ // 特定标签的特定属性
63
+ if (tagName === 'a') {
64
+ const href = node.getAttribute('href');
65
+ if (href && !href.startsWith('javascript')) props.push(`href="${href}"`);
66
+ } else if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {
67
+ if (node.getAttribute('type')) props.push(`type="${node.getAttribute('type')}"`);
68
+ if (node.getAttribute('name')) props.push(`name="${node.getAttribute('name')}"`);
69
+ if (node.getAttribute('placeholder')) props.push(`placeholder="${node.getAttribute('placeholder')}"`);
70
+ if (node.disabled) props.push('disabled');
71
+ if (node.checked) props.push('checked');
72
+ } else if (tagName === 'button') {
73
+ if (node.getAttribute('type')) props.push(`type="${node.getAttribute('type')}"`);
74
+ } else if (tagName === 'img') {
75
+ if (node.getAttribute('alt')) props.push(`alt="${node.getAttribute('alt')}"`);
76
+ } else if (tagName === 'dialog') {
77
+ // 保留 open 属性
78
+ if (node.open) props.push('open');
79
+ }
80
+
81
+ if (props.length > 0) {
82
+ tagStr += ` ${props.join(' ')}`;
83
+ }
84
+
85
+ // 4. 递归子节点 (包含 Shadow DOM 处理)
86
+ let childNodes = Array.from(node.childNodes);
87
+ if (node.shadowRoot) {
88
+ childNodes = [...childNodes, ...Array.from(node.shadowRoot.childNodes)];
89
+ }
90
+
91
+ const children = childNodes
92
+ .map(getSimplifiedDOM)
93
+ .filter(n => n !== null);
94
+
95
+ // 5. 组装输出
96
+ if (children.length === 0) {
97
+ return `<${tagStr} />`;
98
+ }
99
+ return `<${tagStr}>${children.join('')}</${tagName}>`;
100
+ }
101
+
102
+ return getSimplifiedDOM(document.body);
103
+ """
104
+
105
+
106
+ # 使用requests获取html,用于测试是否使用了瑞数和jsl
107
+ def requests_html(url):
108
+ headers = {
109
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
110
+ }
111
+ response = requests.get(url, headers=headers, verify=False)
112
+ response.encoding = "utf-8"
113
+ return response.text, response.status_code
114
+
115
+
116
+ # 使用dp无头模式获取html,用于测试是否使用了其他waf,如移动waf
117
+ def dp_headless_html(url):
118
+ opt = ChromiumOptions().headless(True)
119
+ opt.set_argument('--no-sandbox')
120
+ """创建新的浏览器实例"""
121
+ random_port = random.randint(9934, 10034)
122
+ custom_data_dir = os.path.join(os.path.expanduser('~'), 'DrissionPage', "userData", f"{random_port}")
123
+ opt.set_user_data_path(custom_data_dir) # 设置用户数据路径
124
+ opt.set_local_port(random_port)
125
+ page = ChromiumPage(opt)
126
+ tab = page.latest_tab
127
+ tab.get(url)
128
+ # todo: 目前没有更好的方式,为了数据渲染完全,只能硬等【受网速波动影响比较大】
129
+ time.sleep(10)
130
+ page_html = tab.html
131
+ # 无头浏览器在用完之后一定要记得再page级别进行quit
132
+ page.quit()
133
+ return page_html
134
+
135
+
136
+ # 压缩html
137
+ def compress_html(content, only_text=False):
138
+ doc = html.fromstring(content)
139
+ # 删除 style 和 script 标签
140
+ for element in doc.xpath('//style | //script'):
141
+ element.getparent().remove(element)
142
+
143
+ # 删除 link 标签
144
+ for link in doc.xpath('//link[@rel="stylesheet"]'):
145
+ link.getparent().remove(link)
146
+
147
+ # 删除 meta 标签(新增功能)
148
+ for meta in doc.xpath('//meta'):
149
+ meta.getparent().remove(meta)
150
+
151
+ for svg in doc.xpath('//svg'):
152
+ # 获取 SVG 内的文本内容
153
+ text_content = svg.text_content()
154
+ # 创建一个新的文本节点替换 SVG
155
+ parent = svg.getparent()
156
+ if parent is not None:
157
+ parent.text = (parent.text or '') + text_content
158
+ parent.remove(svg)
159
+
160
+ # 删除 style 属性
161
+ for element in doc.xpath('//*[@style]'):
162
+ element.attrib.pop('style')
163
+
164
+ # 删除所有 on* 事件属性
165
+ for element in doc.xpath('//*'):
166
+ for attr in list(element.attrib.keys()):
167
+ if attr.startswith('on'):
168
+ element.attrib.pop(attr)
169
+
170
+ result = etree.tostring(doc, encoding='unicode')
171
+ result = minify_html.minify(result)
172
+ compress_rate = round(len(content) / len(result) * 100)
173
+ print(f"html压缩比=> {compress_rate}%")
174
+ if not only_text:
175
+ return result, compress_rate
176
+ soup = BeautifulSoup(result, 'html.parser')
177
+ result = soup.get_text(strip=True)
178
+ return result, compress_rate
179
+
180
+
181
+ # 通过cookie判断是否有waf,需要通过遇到的例子,不断的完善cookie判别函数
182
+ def assert_waf_cookie(cookies: list):
183
+ for cookie in cookies:
184
+ cookie_name = cookie['name']
185
+ cookie_value = cookie['value']
186
+ if len(cookie_name) == 13 and len(cookie_value) == 88:
187
+ return True, "瑞数"
188
+ if "_jsl" in cookie_name:
189
+ return True, "加速乐"
190
+ return False, "没有waf"
191
+
192
+
193
+ # 对dp_mcp的消息打包
194
+ def dp_mcp_message_pack(message: str, **kwargs):
195
+ text_obj = {key: value for key, value in kwargs.items()}
196
+ text_obj.update({"message": message})
197
+ return {
198
+ "content": [{
199
+ "type": "text",
200
+ # "text": json.dumps(text_obj, ensure_ascii=False)
201
+ "text": text_obj
202
+ }]
203
+ }
204
+
205
+
206
+ def btyes2Base64Img(target_byte):
207
+ """
208
+ 把byte转为base64,用于传输图片
209
+ :param target_byte:
210
+ :return:
211
+ """
212
+ return "data:image/png;base64," + base64.b64encode(target_byte).decode()
213
+
214
+
215
+ def compress_image_bytes(input_bytes, target_size_mb=1):
216
+ """
217
+ 压缩图片字节数据到目标大小
218
+
219
+ 参数:
220
+ input_bytes: 输入图片的字节数据
221
+ target_size_mb: 目标大小(MB),默认1MB
222
+
223
+ 返回:
224
+ 压缩后的图片字节数据
225
+ """
226
+ target_size = target_size_mb * 1024 * 1024 # 转换为字节
227
+
228
+ # 从字节数据打开图片
229
+ img = Image.open(io.BytesIO(input_bytes))
230
+
231
+ # 如果是PNG或其他格式,转换为RGB
232
+ if img.mode in ('RGBA', 'LA', 'P'):
233
+ img = img.convert('RGB')
234
+
235
+ # 初始质量设置
236
+ quality = 95
237
+
238
+ # 先尝试压缩
239
+ output_buffer = io.BytesIO()
240
+ img.save(output_buffer, 'JPEG', quality=quality, optimize=True)
241
+ output_bytes = output_buffer.getvalue()
242
+
243
+ # 如果文件仍然太大,逐步降低质量
244
+ while len(output_bytes) > target_size and quality > 10:
245
+ quality -= 5
246
+ output_buffer = io.BytesIO()
247
+ img.save(output_buffer, 'JPEG', quality=quality, optimize=True)
248
+ output_bytes = output_buffer.getvalue()
249
+
250
+ # 如果降低质量还不够,尝试缩小尺寸
251
+ if len(output_bytes) > target_size:
252
+ width, height = img.size
253
+
254
+ while len(output_bytes) > target_size and quality > 10:
255
+ # 缩小10%
256
+ width = int(width * 0.9)
257
+ height = int(height * 0.9)
258
+ img_resized = img.resize((width, height), Image.Resampling.LANCZOS)
259
+ output_buffer = io.BytesIO()
260
+ img_resized.save(output_buffer, 'JPEG', quality=quality, optimize=True)
261
+ output_bytes = output_buffer.getvalue()
262
+
263
+ final_size = len(output_bytes) / (1024 * 1024)
264
+ # print(f"压缩完成!")
265
+ # print(f"原始大小: {len(input_bytes) / (1024 * 1024):.2f}MB")
266
+ # print(f"压缩后大小: {final_size:.2f}MB")
267
+ # print(f"最终质量: {quality}")
268
+
269
+ return output_bytes
270
+
271
+ # todo: 大致盘一下各种判定的逻辑【以下的所有压缩比之间的差距均取“绝对值”】
272
+ # 1. 如果requests、无头、有头获取到的压缩比之间从差距都在15%以内,则认定该页面是静态页面,此时优先使用requests请求
273
+ # 2. 如果requests的status_code为特定的412,或者521,则判定是瑞数和jsl。[此时还有一个特点:requests的压缩比会与其他两种方式获取到的压缩比差距非常大(一两千的那种)]
274
+ # 3. 如果requests、无头、有头获取到的压缩比之间差距都在40%以上,则判定该页面只可以用有头采集
275
+ # 4. 如果无头和有头获取到的压缩比之间差距小于15%,但是requests和无头的差距大于40%,则认定该页面可以使用无头浏览器采集
276
+ # 5. 如果requests和有头获取到的压缩比之间差距小于15%,但是无头和有头的差距大于40%,则认定该页面优先使用有头浏览器采集
277
+ # 【此时可能是:1.使用了别的检测无头的waf。2.网站使用瑞数,但是这次请求没有拦截requests(不知道是不是瑞数那边故意设置的),
278
+ # 此时如果想进一步判定是否是瑞数,可以使用有头浏览器取一下cookies,如果cookies里面存在瑞数的cookie,那么就可以断定是瑞数】
@@ -1,11 +0,0 @@
1
- """
2
- 这个文件中提供的工具作为谷歌官方mcp:chrome-devtools-mcp的辅助工具,仅提供功能补充与浏览器实例管理
3
- """
4
- import hashlib
5
- import json
6
- import os
7
- from typing import Any
8
-
9
- from fastmcp import FastMCP
10
-
11
- from tools.browser_manager import BrowserManager
@@ -1,198 +0,0 @@
1
- import time
2
- import random
3
- import os
4
- import minify_html
5
- from DrissionPage import ChromiumPage, ChromiumOptions
6
- from bs4 import BeautifulSoup
7
- from curl_cffi import requests
8
- from lxml import html, etree
9
-
10
- compress_html_js = """
11
- function getSimplifiedDOM(node) {
12
- // 1. 处理文本节点
13
- if (node.nodeType === Node.TEXT_NODE) {
14
- const text = node.textContent.trim();
15
- // 限制文本长度,避免大段文章消耗 token,保留前100个字符通常足够定位
16
- return text ? text.slice(0, 100) + (text.length > 100 ? '...' : '') : null;
17
- }
18
-
19
- // 2. 过滤无用标签
20
- const ignoreTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'IFRAME', 'SVG', 'LINK', 'META'];
21
- if (ignoreTags.includes(node.tagName)) return null;
22
- if (node.nodeType !== Node.ELEMENT_NODE) return null;
23
-
24
- // 3. 过滤不可见元素
25
- const style = window.getComputedStyle(node);
26
- if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return null;
27
- // 过滤宽高太小的元素(往往是埋点空像素)
28
- const rect = node.getBoundingClientRect();
29
- if (rect.width === 0 || rect.height === 0) return null;
30
-
31
- // --- 开始构建标签字符串 ---
32
- const tagName = node.tagName.toLowerCase();
33
- let tagStr = tagName;
34
-
35
- // A. 基础标识符 (ID 和 Class)
36
- if (node.id) tagStr += `#${node.id}`;
37
- if (node.className && typeof node.className === 'string') {
38
- // 过滤掉 Tailwind 等太长且无语义的 class,保留有意义的业务 class
39
- // 这里简单处理,全部保留,让 LLM 自己判断
40
- const classes = node.className.trim().split(/\s+/);
41
- if (classes.length > 0) tagStr += `.${classes.join('.')}`;
42
- }
43
-
44
- // B. 关键属性白名单 (这是你指出问题的核心修复)
45
- const props = [];
46
-
47
- // 通用重要属性
48
- if (node.getAttribute('role')) props.push(`role="${node.getAttribute('role')}"`);
49
- if (node.getAttribute('aria-label')) props.push(`aria-label="${node.getAttribute('aria-label')}"`);
50
- if (node.getAttribute('title')) props.push(`title="${node.getAttribute('title')}"`);
51
-
52
- // 特定标签的特定属性
53
- if (tagName === 'a') {
54
- const href = node.getAttribute('href');
55
- // 只保留有意义的链接,忽略 javascript:;
56
- if (href && !href.startsWith('javascript')) props.push(`href="${href}"`);
57
- } else if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {
58
- if (node.getAttribute('type')) props.push(`type="${node.getAttribute('type')}"`);
59
- if (node.getAttribute('name')) props.push(`name="${node.getAttribute('name')}"`);
60
- if (node.getAttribute('placeholder')) props.push(`placeholder="${node.getAttribute('placeholder')}"`);
61
- if (node.disabled) props.push('disabled');
62
- if (node.checked) props.push('checked');
63
- } else if (tagName === 'button') {
64
- if (node.getAttribute('type')) props.push(`type="${node.getAttribute('type')}"`);
65
- } else if (tagName === 'img') {
66
- if (node.getAttribute('alt')) props.push(`alt="${node.getAttribute('alt')}"`);
67
- }
68
-
69
- if (props.length > 0) {
70
- tagStr += ` ${props.join(' ')}`;
71
- }
72
-
73
- // 4. 递归子节点
74
- const children = Array.from(node.childNodes)
75
- .map(getSimplifiedDOM)
76
- .filter(n => n !== null);
77
-
78
- // 5. 组装输出
79
- // 如果没有子节点,也没有ID/Class,也不是输入框/图片/链接,那这个标签可能只是布局用的 div,可以考虑跳过它直接返回子节点内容
80
- // 但为了保持结构完整,我们暂时保留它
81
- if (children.length === 0) {
82
- // 自闭合标签或空标签
83
- return `<${tagStr} />`;
84
- }
85
- return `<${tagStr}>${children.join('')}</${tagName}>`; // 结束标签只保留 tagName 节省 token
86
- }
87
-
88
- return getSimplifiedDOM(document.body);
89
- """
90
-
91
-
92
- # 使用requests获取html,用于测试是否使用了瑞数和jsl
93
- def requests_html(url):
94
- headers = {
95
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
96
- }
97
- response = requests.get(url, headers=headers, verify=False)
98
- response.encoding = "utf-8"
99
- return response.text, response.status_code
100
-
101
-
102
- # 使用dp无头模式获取html,用于测试是否使用了其他waf,如移动waf
103
- def dp_headless_html(url):
104
- opt = ChromiumOptions().headless(True)
105
- opt.set_argument('--no-sandbox')
106
- """创建新的浏览器实例"""
107
- random_port = random.randint(9934, 10034)
108
- custom_data_dir = os.path.join(os.path.expanduser('~'), 'DrissionPage', "userData", f"{random_port}")
109
- opt.set_user_data_path(custom_data_dir) # 设置用户数据路径
110
- opt.set_local_port(random_port)
111
- page = ChromiumPage(opt)
112
- tab = page.latest_tab
113
- tab.get(url)
114
- # todo: 目前没有更好的方式,为了数据渲染完全,只能硬等【受网速波动影响比较大】
115
- time.sleep(10)
116
- page_html = tab.html
117
- # 无头浏览器在用完之后一定要记得再page级别进行quit
118
- page.quit()
119
- return page_html
120
-
121
-
122
- # 压缩html
123
- def compress_html(content, only_text=False):
124
- doc = html.fromstring(content)
125
- # 删除 style 和 script 标签
126
- for element in doc.xpath('//style | //script'):
127
- element.getparent().remove(element)
128
-
129
- # 删除 link 标签
130
- for link in doc.xpath('//link[@rel="stylesheet"]'):
131
- link.getparent().remove(link)
132
-
133
- # 删除 meta 标签(新增功能)
134
- for meta in doc.xpath('//meta'):
135
- meta.getparent().remove(meta)
136
-
137
- for svg in doc.xpath('//svg'):
138
- # 获取 SVG 内的文本内容
139
- text_content = svg.text_content()
140
- # 创建一个新的文本节点替换 SVG
141
- parent = svg.getparent()
142
- if parent is not None:
143
- parent.text = (parent.text or '') + text_content
144
- parent.remove(svg)
145
-
146
- # 删除 style 属性
147
- for element in doc.xpath('//*[@style]'):
148
- element.attrib.pop('style')
149
-
150
- # 删除所有 on* 事件属性
151
- for element in doc.xpath('//*'):
152
- for attr in list(element.attrib.keys()):
153
- if attr.startswith('on'):
154
- element.attrib.pop(attr)
155
-
156
- result = etree.tostring(doc, encoding='unicode')
157
- result = minify_html.minify(result)
158
- compress_rate = round(len(content) / len(result) * 100)
159
- print(f"html压缩比=> {compress_rate}%")
160
- if not only_text:
161
- return result, compress_rate
162
- soup = BeautifulSoup(result, 'html.parser')
163
- result = soup.get_text(strip=True)
164
- return result, compress_rate
165
-
166
-
167
- # 通过cookie判断是否有waf,需要通过遇到的例子,不断的完善cookie判别函数
168
- def assert_waf_cookie(cookies: list):
169
- for cookie in cookies:
170
- cookie_name = cookie['name']
171
- cookie_value = cookie['value']
172
- if len(cookie_name) == 13 and len(cookie_value) == 88:
173
- return True, "瑞数"
174
- if "_jsl" in cookie_name:
175
- return True, "加速乐"
176
- return False, "没有waf"
177
-
178
-
179
- # 对dp_mcp的消息打包
180
- def dp_mcp_message_pack(message: str, **kwargs):
181
- text_obj = {key: value for key, value in kwargs.items()}
182
- text_obj.update({"message": message})
183
- return {
184
- "content": [{
185
- "type": "text",
186
- # "text": json.dumps(text_obj, ensure_ascii=False)
187
- "text": text_obj
188
- }]
189
- }
190
-
191
- # todo: 大致盘一下各种判定的逻辑【以下的所有压缩比之间的差距均取“绝对值”】
192
- # 1. 如果requests、无头、有头获取到的压缩比之间从差距都在15%以内,则认定该页面是静态页面,此时优先使用requests请求
193
- # 2. 如果requests的status_code为特定的412,或者521,则判定是瑞数和jsl。[此时还有一个特点:requests的压缩比会与其他两种方式获取到的压缩比差距非常大(一两千的那种)]
194
- # 3. 如果requests、无头、有头获取到的压缩比之间差距都在40%以上,则判定该页面只可以用有头采集
195
- # 4. 如果无头和有头获取到的压缩比之间差距小于15%,但是requests和无头的差距大于40%,则认定该页面可以使用无头浏览器采集
196
- # 5. 如果requests和有头获取到的压缩比之间差距小于15%,但是无头和有头的差距大于40%,则认定该页面优先使用有头浏览器采集
197
- # 【此时可能是:1.使用了别的检测无头的waf。2.网站使用瑞数,但是这次请求没有拦截requests(不知道是不是瑞数那边故意设置的),
198
- # 此时如果想进一步判定是否是瑞数,可以使用有头浏览器取一下cookies,如果cookies里面存在瑞数的cookie,那么就可以断定是瑞数】