scripts/multi_search.py
34.9 KB| 1 | #!/usr/bin/env python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | """ |
| 4 | multi_search.py — 多搜索引擎聚合检索(零第三方依赖) |
| 5 | |
| 6 | 配合 multi-search-engine 技能使用。仅依赖 Python 3.7+ 标准库。 |
| 7 | |
| 8 | 两种模式: |
| 9 | 1. 链接模式(默认,不发起网络请求):为选定引擎生成可点击的搜索链接,任何环境都可用。 |
| 10 | 2. 抓取模式(--fetch):以浏览器身份请求公开搜索页,尽力提取标题与链接, |
| 11 | 跨引擎去重后输出 Markdown / JSON 报告。单引擎失败不影响其他引擎。 |
| 12 | |
| 13 | 安全与合规: |
| 14 | - 只访问公开的搜索引擎结果页,不需要任何 API Key; |
| 15 | - Cookie 仅在单个引擎的一次检索过程中暂存于内存(遇 403/429 时访问首页建立会话后 |
| 16 | 重试一次),不读写磁盘、会话结束即丢弃,不模拟登录; |
| 17 | - 顺序请求、请求间隔默认 1.5 秒、单引擎最多重试 1 次,不绕过验证码; |
| 18 | - 默认不写文件,仅当显式传入 --output 时才保存报告。 |
| 19 | |
| 20 | 示例(Windows 用 python,macOS/Linux 可用 python3): |
| 21 | python multi_search.py --list-engines |
| 22 | python multi_search.py "Python 教程" |
| 23 | python multi_search.py "react hooks" -e bing-cn,baidu --fetch |
| 24 | python multi_search.py "AI 新闻" --cn --time d --json |
| 25 | python multi_search.py "site:github.com transformer" -e google --fetch |
| 26 | """ |
| 27 | |
| 28 | import argparse |
| 29 | import base64 |
| 30 | import datetime as _dt |
| 31 | import gzip |
| 32 | import http.cookiejar |
| 33 | import html as _html |
| 34 | import io |
| 35 | import json |
| 36 | import re |
| 37 | import sys |
| 38 | import time |
| 39 | import urllib.error |
| 40 | import urllib.parse |
| 41 | import urllib.request |
| 42 | from html.parser import HTMLParser |
| 43 | |
| 44 | # Windows 控制台 UTF-8 输出(Python 3.7+) |
| 45 | try: |
| 46 | sys.stdout.reconfigure(encoding="utf-8") |
| 47 | except Exception: |
| 48 | pass |
| 49 | |
| 50 | USER_AGENT = ( |
| 51 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " |
| 52 | "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" |
| 53 | ) |
| 54 | |
| 55 | # 跟踪参数:去重时丢弃,避免同一页面被识别成不同结果 |
| 56 | TRACKING_PARAMS = { |
| 57 | "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", |
| 58 | "fbclid", "gclid", "spm", "from", "isappinstalled", "ie", "f", |
| 59 | "rsv_bp", "rsv_sug3", "oq", |
| 60 | } |
| 61 | |
| 62 | # 引擎注册表:抓取方式经过 2026 年可用性核对 |
| 63 | # access: direct=中国大陆可直连 intl=需国际网络环境 |
| 64 | # antibot: low/med/high 表示公开结果页对非浏览器抓取的友好程度 |
| 65 | ENGINES = { |
| 66 | # ---------- 国内 7 ---------- |
| 67 | "bing-cn": { |
| 68 | "name": "必应中国", "group": "cn", "access": "direct", "antibot": "low", |
| 69 | "best": "综合网页、英文资料国内直出,抓取成功率最高,默认首选", |
| 70 | "url": "https://cn.bing.com/search?q={q}&ensearch=0", |
| 71 | }, |
| 72 | "bing-int": { |
| 73 | "name": "必应国际版(国内入口)", "group": "cn", "access": "direct", "antibot": "low", |
| 74 | "best": "在大陆直连获取国际结果,无需国际网络", |
| 75 | "url": "https://cn.bing.com/search?q={q}&ensearch=1", |
| 76 | }, |
| 77 | "baidu": { |
| 78 | "name": "百度", "group": "cn", "access": "direct", "antibot": "high", |
| 79 | "best": "中文资讯、百家号、贴吧、国内长尾信息", |
| 80 | "url": "https://www.baidu.com/s?wd={q}&rn=10", |
| 81 | }, |
| 82 | "so360": { |
| 83 | "name": "360搜索", "group": "cn", "access": "direct", "antibot": "med", |
| 84 | "best": "中文资讯、问答内容交叉验证", |
| 85 | "url": "https://www.so.com/s?q={q}", |
| 86 | }, |
| 87 | "sogou": { |
| 88 | "name": "搜狗", "group": "cn", "access": "direct", "antibot": "med", |
| 89 | "best": "微信/知乎内容收录、微信公众号文章(配合 weixin 引擎)", |
| 90 | "url": "https://www.sogou.com/web?query={q}", |
| 91 | }, |
| 92 | "weixin": { |
| 93 | "name": "微信搜索", "group": "cn", "access": "direct", "antibot": "high", |
| 94 | "best": "微信公众号文章,频繁请求会出现验证码", |
| 95 | "url": "https://weixin.sogou.com/weixin?type=2&query={q}", |
| 96 | }, |
| 97 | "shenma": { |
| 98 | "name": "神马搜索", "group": "cn", "access": "direct", "antibot": "med", |
| 99 | "best": "移动视角的中文长尾内容(UC/阿里系)", |
| 100 | "url": "https://m.sm.cn/s?q={q}", |
| 101 | }, |
| 102 | # ---------- 国际 9 ---------- |
| 103 | "duckduckgo": { |
| 104 | "name": "DuckDuckGo", "group": "global", "access": "intl", "antibot": "low", |
| 105 | "best": "隐私无追踪、无埋点,html/lite 无 JS 端点结构稳定,国际环境首选", |
| 106 | "url": "https://html.duckduckgo.com/html/?q={q}", |
| 107 | "fetch": {"method": "POST", "post_url": "https://html.duckduckgo.com/html/", |
| 108 | "fallback": "https://lite.duckduckgo.com/lite/?q={q}"}, |
| 109 | }, |
| 110 | "google": { |
| 111 | "name": "Google", "group": "global", "access": "intl", "antibot": "med", |
| 112 | "best": "英文技术资料、官方文档、学术资源覆盖面最广", |
| 113 | "url": "https://www.google.com/search?q={q}", |
| 114 | "fetch_url": "https://www.google.com/search?q={q}&gbv=1&num=10", |
| 115 | }, |
| 116 | "google-hk": { |
| 117 | "name": "Google香港", "group": "global", "access": "intl", "antibot": "med", |
| 118 | "best": "Google 备用入口,中文结果权重略高", |
| 119 | "url": "https://www.google.com.hk/search?q={q}", |
| 120 | "fetch_url": "https://www.google.com.hk/search?q={q}&gbv=1&num=10", |
| 121 | }, |
| 122 | "ecosia": { |
| 123 | "name": "Ecosia", "group": "global", "access": "intl", "antibot": "low", |
| 124 | "best": "基于 Bing 索引,反爬宽松,Google 不可用时的国际平替", |
| 125 | "url": "https://www.ecosia.org/search?q={q}", |
| 126 | }, |
| 127 | "yahoo": { |
| 128 | "name": "Yahoo", "group": "global", "access": "intl", "antibot": "med", |
| 129 | "best": "英文/日文资讯、老站收录", |
| 130 | "url": "https://search.yahoo.com/search?p={q}", |
| 131 | }, |
| 132 | "startpage": { |
| 133 | "name": "Startpage", "group": "global", "access": "intl", "antibot": "high", |
| 134 | "best": "Google 结果源 + 隐私保护,抓取常被拦截", |
| 135 | "url": "https://www.startpage.com/sp/search?query={q}", |
| 136 | }, |
| 137 | "brave": { |
| 138 | "name": "Brave", "group": "global", "access": "intl", "antibot": "high", |
| 139 | "best": "独立索引、技术社区内容,需完整浏览器指纹,脚本成功率低", |
| 140 | "url": "https://search.brave.com/search?q={q}", |
| 141 | }, |
| 142 | "qwant": { |
| 143 | "name": "Qwant", "group": "global", "access": "intl", "antibot": "high", |
| 144 | "best": "欧盟隐私引擎,脚本成功率低,建议浏览器使用", |
| 145 | "url": "https://www.qwant.com/?q={q}", |
| 146 | }, |
| 147 | "wolframalpha": { |
| 148 | "name": "WolframAlpha", "group": "global", "access": "intl", "antibot": "med", |
| 149 | "best": "数学计算、单位换算、汇率、日期等结构化知识(非网页检索)", |
| 150 | "url": "https://www.wolframalpha.com/input?i={q}", |
| 151 | "extract": False, |
| 152 | }, |
| 153 | } |
| 154 | |
| 155 | # 垂直站点(第 17+ 个“加分项”,不计入 16 引擎承诺,适合定向检索) |
| 156 | VERTICAL_ENGINES = { |
| 157 | "github": ("GitHub", "https://github.com/search?q={q}&type=repositories"), |
| 158 | "stackoverflow": ("Stack Overflow", "https://stackoverflow.com/search?q={q}"), |
| 159 | "zhihu": ("知乎", "https://www.zhihu.com/search?type=content&q={q}"), |
| 160 | "bilibili": ("哔哩哔哩", "https://search.bilibili.com/all?keyword={q}"), |
| 161 | "toutiao": ("今日头条", "https://so.toutiao.com/search?keyword={q}"), |
| 162 | "juejin": ("掘金", "https://juejin.cn/search?query={q}"), |
| 163 | "scholar": ("Google学术", "https://scholar.google.com/scholar?q={q}"), |
| 164 | "baiduxs": ("百度学术", "https://xueshu.baidu.com/s?wd={q}"), |
| 165 | "weibo": ("微博", "https://s.weibo.com/weibo?q={q}"), |
| 166 | } |
| 167 | |
| 168 | # Google 系时间过滤(tbs=qdr) |
| 169 | TIME_CODES = {"h": "qdr:h", "d": "qdr:d", "w": "qdr:w", "m": "qdr:m", "y": "qdr:y"} |
| 170 | |
| 171 | CN_DEFAULT = ["bing-cn", "baidu", "sogou"] |
| 172 | GLOBAL_DEFAULT = ["duckduckgo", "google", "ecosia"] |
| 173 | |
| 174 | |
| 175 | def build_url(engine_id, query, time_code=None): |
| 176 | """根据引擎模板生成搜索链接(链接模式与抓取模式共用)。""" |
| 177 | if engine_id in ENGINES: |
| 178 | tpl = ENGINES[engine_id]["url"] |
| 179 | else: |
| 180 | tpl = VERTICAL_ENGINES[engine_id][1] |
| 181 | q = urllib.parse.quote(query, safe=":=") |
| 182 | url = tpl.format(q=q) |
| 183 | if time_code and engine_id in ("google", "google-hk"): |
| 184 | url += "&tbs=" + TIME_CODES[time_code] |
| 185 | elif time_code and engine_id == "sogou": |
| 186 | url += "&tsn=" + {"d": "1", "w": "2", "m": "3", "y": "4"}[time_code] |
| 187 | elif time_code and engine_id == "duckduckgo": |
| 188 | url += "&df=" + time_code |
| 189 | return url |
| 190 | |
| 191 | |
| 192 | # ------------------------- 抓取与解析 ------------------------- |
| 193 | |
| 194 | class _AnchorParser(HTMLParser): |
| 195 | """收集页面中的 <a href> 及其内部文字。""" |
| 196 | |
| 197 | def __init__(self): |
| 198 | super().__init__(convert_charrefs=True) |
| 199 | self.anchors = [] |
| 200 | self._href = None |
| 201 | self._text = [] |
| 202 | |
| 203 | def handle_starttag(self, tag, attrs): |
| 204 | if tag == "a": |
| 205 | self._href = dict(attrs).get("href") |
| 206 | self._text = [] |
| 207 | |
| 208 | def handle_data(self, data): |
| 209 | if self._href is not None: |
| 210 | t = data.strip() |
| 211 | if t: |
| 212 | self._text.append(t) |
| 213 | |
| 214 | def handle_endtag(self, tag): |
| 215 | if tag == "a" and self._href is not None: |
| 216 | title = " ".join(self._text).strip() |
| 217 | if title: |
| 218 | self.anchors.append((self._href, title)) |
| 219 | self._href = None |
| 220 | self._text = [] |
| 221 | |
| 222 | |
| 223 | def _decode(body, headers): |
| 224 | """gzip 解压 + 编码探测。""" |
| 225 | if headers.get("Content-Encoding", "") == "gzip": |
| 226 | body = gzip.GzipFile(fileobj=io.BytesIO(body)).read() |
| 227 | charset = headers.get_content_charset() |
| 228 | for enc in (charset, "utf-8", "gb18030"): |
| 229 | if not enc: |
| 230 | continue |
| 231 | try: |
| 232 | return body.decode(enc) |
| 233 | except (UnicodeDecodeError, LookupError): |
| 234 | continue |
| 235 | return body.decode("utf-8", errors="replace") |
| 236 | |
| 237 | |
| 238 | def new_session(): |
| 239 | """新建一个仅存活于单次引擎检索的内存 Cookie 会话(不写入磁盘)。""" |
| 240 | jar = http.cookiejar.CookieJar() |
| 241 | opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) |
| 242 | return opener, jar |
| 243 | |
| 244 | |
| 245 | def http_get(url, timeout, opener=None): |
| 246 | req = urllib.request.Request(url, headers={ |
| 247 | "User-Agent": USER_AGENT, |
| 248 | "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", |
| 249 | "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", |
| 250 | "Accept-Encoding": "gzip", |
| 251 | }) |
| 252 | _open = opener.open if opener is not None else urllib.request.urlopen |
| 253 | with _open(req, timeout=timeout) as resp: |
| 254 | return resp.status, _decode(resp.read(), resp.headers), resp.geturl() |
| 255 | |
| 256 | |
| 257 | def http_post(url, data, timeout, opener=None): |
| 258 | body = urllib.parse.urlencode(data).encode("utf-8") |
| 259 | req = urllib.request.Request(url, data=body, headers={ |
| 260 | "User-Agent": USER_AGENT, |
| 261 | "Content-Type": "application/x-www-form-urlencoded", |
| 262 | "Accept": "text/html,application/xhtml+xml,*/*;q=0.8", |
| 263 | "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", |
| 264 | "Accept-Encoding": "gzip", |
| 265 | "Origin": "https://html.duckduckgo.com", |
| 266 | "Referer": "https://html.duckduckgo.com/", |
| 267 | }) |
| 268 | _open = opener.open if opener is not None else urllib.request.urlopen |
| 269 | with _open(req, timeout=timeout) as resp: |
| 270 | return resp.status, _decode(resp.read(), resp.headers), resp.geturl() |
| 271 | |
| 272 | |
| 273 | def unwrap_ddg(href): |
| 274 | """把 duckduckgo.com/l/?uddg=<真实URL> 还原成目标地址。""" |
| 275 | if "duckduckgo.com/l/" in href: |
| 276 | qs = urllib.parse.urlparse(href).query |
| 277 | uddg = urllib.parse.parse_qs(qs).get("uddg", [""])[0] |
| 278 | if uddg: |
| 279 | return uddg |
| 280 | return href |
| 281 | |
| 282 | |
| 283 | def unwrap_bing(href): |
| 284 | """把 bing.com/ck/a?...&u=a1<base64url> 跳转链接还原成目标地址。""" |
| 285 | if "bing.com/ck/a" in href: |
| 286 | u = urllib.parse.parse_qs(urllib.parse.urlparse(href).query).get("u", [""])[0] |
| 287 | if u.startswith("a1"): |
| 288 | raw = u[2:] |
| 289 | raw += "=" * (-len(raw) % 4) |
| 290 | try: |
| 291 | return base64.urlsafe_b64decode(raw).decode("utf-8") |
| 292 | except Exception: |
| 293 | return href |
| 294 | return href |
| 295 | |
| 296 | |
| 297 | def unwrap_yahoo(href): |
| 298 | """Yahoo 跳转链接 r.search.yahoo.com 路径段中的 RU=<真实URL> 还原。""" |
| 299 | if "r.search.yahoo.com/" in href and "/RU=" in href: |
| 300 | tail = href.split("/RU=", 1)[1] |
| 301 | target = tail.split("/", 1)[0] |
| 302 | if target: |
| 303 | return urllib.parse.unquote(target) |
| 304 | return href |
| 305 | |
| 306 | |
| 307 | def unwrap_google(href): |
| 308 | """Google 基础版 /url?q=<目标>&sa=... 跳转还原。""" |
| 309 | if href.startswith("/url?") or href.startswith("https://www.google.com/url?") \ |
| 310 | or href.startswith("https://www.google.com.hk/url?"): |
| 311 | qs = href.split("?", 1)[1] |
| 312 | target = urllib.parse.parse_qs(qs).get("q", [""])[0] |
| 313 | if target: |
| 314 | return target |
| 315 | return href |
| 316 | |
| 317 | |
| 318 | # 各引擎自身域名 + 允许保留的结果跳转路径 |
| 319 | _OWN_HOSTS = { |
| 320 | "bing-cn": {"cn.bing.com", "www.bing.com", "bing.com"}, |
| 321 | "bing-int": {"cn.bing.com", "www.bing.com", "bing.com"}, |
| 322 | "baidu": {"www.baidu.com", "baidu.com"}, |
| 323 | "so360": {"www.so.com", "so.com"}, |
| 324 | "sogou": {"www.sogou.com", "sogou.com"}, |
| 325 | "shenma": {"m.sm.cn", "sm.cn", "lmda.sm.cn"}, |
| 326 | "weixin": {"weixin.sogou.com", "www.sogou.com"}, |
| 327 | "duckduckgo": {"duckduckgo.com", "html.duckduckgo.com", "lite.duckduckgo.com"}, |
| 328 | "google": {"www.google.com", "google.com"}, |
| 329 | "google-hk": {"www.google.com.hk", "google.com.hk"}, |
| 330 | "ecosia": {"www.ecosia.org", "ecosia.org"}, |
| 331 | "yahoo": {"search.yahoo.com", "yahoo.com", "r.search.yahoo.com"}, |
| 332 | "startpage": {"www.startpage.com", "startpage.com"}, |
| 333 | "brave": {"search.brave.com", "brave.com"}, |
| 334 | "qwant": {"www.qwant.com", "qwant.com"}, |
| 335 | } |
| 336 | |
| 337 | # 站内域名下这些路径是“结果跳转”,保留;其余站内链接视为导航/垂直页丢弃 |
| 338 | _WRAPPER_PATHS = ("/link?", "/ck/a", "/url?", "/l/?", "/RU=", "/jump") |
| 339 | |
| 340 | |
| 341 | def is_internal_nav(engine_id, url): |
| 342 | host = urllib.parse.urlparse(url).netloc.lower() |
| 343 | if host not in _OWN_HOSTS.get(engine_id, set()): |
| 344 | return False |
| 345 | pathq = urllib.parse.urlparse(url).path + "?" + urllib.parse.urlparse(url).query |
| 346 | return not any(w in pathq for w in _WRAPPER_PATHS) |
| 347 | |
| 348 | |
| 349 | def is_result_link(engine_id, href, title): |
| 350 | if not href or len(title) < 6: |
| 351 | return False |
| 352 | href = href.strip() |
| 353 | low = href.lower() |
| 354 | if low.startswith(("javascript:", "#", "mailto:")): |
| 355 | return False |
| 356 | # 明确保留的引擎跳转链接 |
| 357 | if engine_id == "baidu" and "baidu.com/link?url=" in low: |
| 358 | return True |
| 359 | if engine_id in ("so360", "sogou", "shenma") and ("/link?" in low or "/jump" in low): |
| 360 | return True |
| 361 | if engine_id == "weixin" and "mp.weixin.qq.com" in low: |
| 362 | return True |
| 363 | if low.startswith("http"): |
| 364 | host = urllib.parse.urlparse(href).netloc.lower() |
| 365 | own_hosts = _OWN_HOSTS.get(engine_id, set()) |
| 366 | if host not in own_hosts: |
| 367 | return True |
| 368 | # 站内但属于结果跳转链接 |
| 369 | if "baidu.com/link?url=" in low or "bing.com/ck/a" in low: |
| 370 | return True |
| 371 | return False |
| 372 | |
| 373 | |
| 374 | def normalize_url(url): |
| 375 | """URL 规范化用于去重。""" |
| 376 | try: |
| 377 | p = urllib.parse.urlparse(url) |
| 378 | host = p.netloc.lower().replace("www.", "") |
| 379 | qs = [(k, v) for k, v in urllib.parse.parse_qsl(p.query) |
| 380 | if k.lower() not in TRACKING_PARAMS] |
| 381 | path = p.path.rstrip("/") |
| 382 | query = urllib.parse.urlencode(sorted(qs)) |
| 383 | return urllib.parse.urlunparse((p.scheme.lower(), host, path, "", query, "")) |
| 384 | except Exception: |
| 385 | return url |
| 386 | |
| 387 | |
| 388 | # ------------------------- 搜索引擎专属解析 ------------------------- |
| 389 | # 各主流引擎的结果块结构不同,精准提取 <h2>/<h3> 标题锚点, |
| 390 | # 避免把面包屑、<cite> 域名、导航链接误当成结果。 |
| 391 | |
| 392 | def _clean_text(raw): |
| 393 | text = re.sub(r"<[^>]+>", "", raw) |
| 394 | text = _html.unescape(text) |
| 395 | text = re.sub(r"\s+", " ", text).strip() |
| 396 | # 去掉引擎追加在标题尾部的域名展示,如 "教程 — www.baidu.com" |
| 397 | text = re.sub(r"\s+[—–\-|]\s*(?:https?://)?(?:[a-z0-9-]+\.)+[a-z]{2,}(?:[/?#]\S*)?$", |
| 398 | "", text, flags=re.I) |
| 399 | return text.strip(" —–-|") |
| 400 | |
| 401 | |
| 402 | # 推荐搜索/广告块等非结果标题噪声 |
| 403 | _NOISE_TITLES = ("其他人还搜", "相关搜索", "进一步探索", "更多相关", "查看全部", |
| 404 | "大家还在搜", "为您推荐") |
| 405 | |
| 406 | # 广告/点击监测中转域名(非真实内容页) |
| 407 | _TRACKER_HOSTS = {"e.so.com", "p.baidu.com", "pos.baidu.com", "e.baidu.com"} |
| 408 | |
| 409 | |
| 410 | def is_noise(title, href): |
| 411 | if any(n in title for n in _NOISE_TITLES): |
| 412 | return True |
| 413 | try: |
| 414 | if urllib.parse.urlparse(href).netloc.lower() in _TRACKER_HOSTS: |
| 415 | return True |
| 416 | except Exception: |
| 417 | return True |
| 418 | return False |
| 419 | |
| 420 | |
| 421 | def _take(patterns, page, limit): |
| 422 | """按一组 (href_group, title_group) 正则依次提取,命中即返回。""" |
| 423 | out, seen = [], set() |
| 424 | for pat in patterns: |
| 425 | for m in re.finditer(pat, page, flags=re.S | re.I): |
| 426 | href, title = m.group(1), _clean_text(m.group(2)) |
| 427 | if not href or len(title) < 4 or is_noise(title, href): |
| 428 | continue |
| 429 | key = normalize_url(href) |
| 430 | if key in seen: |
| 431 | continue |
| 432 | seen.add(key) |
| 433 | out.append({"title": title, "url": href}) |
| 434 | if len(out) >= limit: |
| 435 | return out |
| 436 | if out: |
| 437 | return out |
| 438 | return out |
| 439 | |
| 440 | |
| 441 | def extract_bing(page, limit): |
| 442 | # <li class="b_algo"><h2><a href="真实链接或 ck/a 跳转">标题</a></h2> |
| 443 | return _take([r'<h2[^>]*>\s*<a\b[^>]*?href="([^"]+)"[^>]*>(.*?)</a>'], page, limit) |
| 444 | |
| 445 | |
| 446 | def extract_h3_anchor(page, limit): |
| 447 | """百度/360/搜狗/Yahoo:解析 h3 内首个 a 标签。 |
| 448 | |
| 449 | 360 把真实地址放在 data-mdurl 属性,href 是 /link 中转,优先取 data-mdurl。 |
| 450 | """ |
| 451 | out, seen = [], set() |
| 452 | for block in re.finditer(r"<h3[^>]*>(.*?)</h3>", page, flags=re.S | re.I): |
| 453 | am = re.search(r"<a\b([^>]*)>(.*?)</a>", block.group(1), flags=re.S | re.I) |
| 454 | if not am: |
| 455 | continue |
| 456 | attrs, inner = am.group(1), am.group(2) |
| 457 | hm = re.search(r'href="([^"]+)"', attrs) |
| 458 | if not hm: |
| 459 | continue |
| 460 | href = hm.group(1) |
| 461 | md = re.search(r'data-mdurl="([^"]+)"', attrs) |
| 462 | if md and md.group(1).startswith("http"): |
| 463 | href = _html.unescape(md.group(1)) |
| 464 | title = _clean_text(inner) |
| 465 | if len(title) < 4 or is_noise(title, href): |
| 466 | continue |
| 467 | key = normalize_url(href) |
| 468 | if key in seen: |
| 469 | continue |
| 470 | seen.add(key) |
| 471 | out.append({"title": title, "url": href}) |
| 472 | if len(out) >= limit: |
| 473 | break |
| 474 | return out |
| 475 | |
| 476 | |
| 477 | def extract_ddg(page, limit): |
| 478 | out, seen = [], set() |
| 479 | for m in re.finditer(r'<a\b([^>]*class="result__a"[^>]*)>(.*?)</a>', page, flags=re.S): |
| 480 | attrs, inner = m.group(1), m.group(2) |
| 481 | hm = re.search(r'href="([^"]+)"', attrs) |
| 482 | if not hm: |
| 483 | continue |
| 484 | href, title = hm.group(1), _clean_text(inner) |
| 485 | if len(title) < 4: |
| 486 | continue |
| 487 | key = normalize_url(href) |
| 488 | if key in seen: |
| 489 | continue |
| 490 | seen.add(key) |
| 491 | out.append({"title": title, "url": href}) |
| 492 | if len(out) >= limit: |
| 493 | break |
| 494 | return out |
| 495 | |
| 496 | |
| 497 | def extract_google(page, limit): |
| 498 | # 基础版:<a href="..."><h3>标题</h3></a>(href 可能是 /url?q= 跳转) |
| 499 | return _take([r'<a\b[^>]*?href="([^"]+)"[^>]*>(?:(?!</a>).)*?<h3[^>]*>(.*?)</h3>'], |
| 500 | page, limit) |
| 501 | |
| 502 | |
| 503 | def extract_weixin(page, limit): |
| 504 | return _take([r'<a\b[^>]*?href="(https://mp\.weixin\.qq\.com/[^"]+)"[^>]*>(.*?)</a>'], |
| 505 | page, limit) |
| 506 | |
| 507 | |
| 508 | def extract_github(page, limit): |
| 509 | # 仓库搜索结果链接(2025+ 新版 search-title 结构 / 旧版 v-align-middle) |
| 510 | return _take([ |
| 511 | r'class="search-title[^"]*"[^>]*>\s*<a\b[^>]*?href="(/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)"[^>]*>(.*?)</a>', |
| 512 | r'<a\b[^>]*?data-testid="results-list-item-title"[^>]*?href="(/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)"[^>]*>(.*?)</a>', |
| 513 | r'<a\b[^>]*?class="v-align-middle"[^>]*?href="(/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)"[^>]*>(.*?)</a>', |
| 514 | ], page, limit) |
| 515 | |
| 516 | |
| 517 | # 引擎 → 专属解析器;未列出的引擎退回全页锚点扫描 |
| 518 | _EXTRACTORS = { |
| 519 | "bing-cn": extract_bing, "bing-int": extract_bing, |
| 520 | "baidu": extract_h3_anchor, "so360": extract_h3_anchor, |
| 521 | "sogou": extract_h3_anchor, "yahoo": extract_h3_anchor, |
| 522 | "stackoverflow": extract_h3_anchor, |
| 523 | "duckduckgo": extract_ddg, |
| 524 | "google": extract_google, "google-hk": extract_google, |
| 525 | "weixin": extract_weixin, "github": extract_github, |
| 526 | } |
| 527 | |
| 528 | |
| 529 | def extract_results(engine_id, page_html, limit): |
| 530 | parser_fn = _EXTRACTORS.get(engine_id) |
| 531 | if parser_fn is not None: |
| 532 | raw = parser_fn(page_html, limit) |
| 533 | else: |
| 534 | parser = _AnchorParser() |
| 535 | try: |
| 536 | parser.feed(page_html) |
| 537 | except Exception: |
| 538 | pass |
| 539 | raw = [{"title": t, "url": h} for h, t in parser.anchors |
| 540 | if is_result_link(engine_id, h, t)][:limit] |
| 541 | out, seen = [], set() |
| 542 | for item in raw: |
| 543 | href = item["url"].strip() |
| 544 | if href.startswith("//"): |
| 545 | href = "https:" + href |
| 546 | elif href.startswith("/"): |
| 547 | base = ENGINES[engine_id]["url"] if engine_id in ENGINES \ |
| 548 | else VERTICAL_ENGINES[engine_id][1] |
| 549 | href = urllib.parse.urljoin(base, href) |
| 550 | href = unwrap_yahoo(href) |
| 551 | href = unwrap_ddg(href) |
| 552 | href = unwrap_bing(href) |
| 553 | href = unwrap_google(href) |
| 554 | href = _html.unescape(href) |
| 555 | title = _html.unescape(re.sub(r"\s+", " ", item["title"])) |
| 556 | if is_noise(title, href) or is_internal_nav(engine_id, href): |
| 557 | continue |
| 558 | key = normalize_url(href) |
| 559 | if key in seen: |
| 560 | continue |
| 561 | seen.add(key) |
| 562 | out.append({"title": title, "url": href}) |
| 563 | if len(out) >= limit: |
| 564 | break |
| 565 | return out |
| 566 | |
| 567 | |
| 568 | # ------------------------- DDG 摘要(结构稳定,单独解析) ------------------------- |
| 569 | |
| 570 | def extract_ddg_snippets(page_html): |
| 571 | """DuckDuckGo html 端点的摘要文本,按出现顺序返回,供报告补充。""" |
| 572 | return [_html.unescape(re.sub(r"<[^>]+>", "", s)).strip() |
| 573 | for s in re.findall(r'class="result__snippet"[^>]*>(.*?)</a>', |
| 574 | page_html, flags=re.S)][:10] |
| 575 | |
| 576 | |
| 577 | # ------------------------- 引擎执行 ------------------------- |
| 578 | |
| 579 | def _do_request(engine_id, fetch_tpl, post_cfg, query, q, args, opener): |
| 580 | """用给定会话执行一次检索请求,返回页面 HTML。""" |
| 581 | url = fetch_tpl.format(q=q) |
| 582 | if post_cfg and post_cfg.get("method") == "POST": |
| 583 | data = {"q": query} |
| 584 | if args.time: |
| 585 | data["df"] = args.time |
| 586 | try: |
| 587 | _, page, _ = http_post(post_cfg["post_url"], data, args.timeout, opener) |
| 588 | except Exception: |
| 589 | _, page, _ = http_get(post_cfg["fallback"].format(q=q), args.timeout, opener) |
| 590 | return page |
| 591 | return http_get(url, args.timeout, opener)[1] |
| 592 | |
| 593 | |
| 594 | def search_one(engine_id, query, args): |
| 595 | """抓取单个引擎,返回 (results, error)。 |
| 596 | |
| 597 | 会话管理(对齐原始工作流):每个引擎使用独立的内存 CookieJar; |
| 598 | 首次请求遇 403/418/429/503 时,先 GET 一次引擎首页建立会话, |
| 599 | 等待 2 秒后仅重试 1 次。Cookie 不落盘、函数返回即丢弃。 |
| 600 | """ |
| 601 | if engine_id in ENGINES: |
| 602 | meta = ENGINES[engine_id] |
| 603 | fetch_tpl = meta.get("fetch_url", meta["url"]) |
| 604 | post_cfg = meta.get("fetch") |
| 605 | req_host_url = post_cfg["post_url"] if post_cfg else fetch_tpl |
| 606 | else: # 垂直站点 |
| 607 | meta, post_cfg = {"group": "vertical"}, None |
| 608 | fetch_tpl = VERTICAL_ENGINES[engine_id][1] |
| 609 | req_host_url = fetch_tpl |
| 610 | q = urllib.parse.quote(query, safe=":=") |
| 611 | if args.time and engine_id in ("google", "google-hk"): |
| 612 | fetch_tpl += "&tbs=" + TIME_CODES[args.time] |
| 613 | |
| 614 | opener, _jar = new_session() |
| 615 | try: |
| 616 | page = _do_request(engine_id, fetch_tpl, post_cfg, query, q, args, opener) |
| 617 | except urllib.error.HTTPError as e: |
| 618 | if e.code not in (403, 418, 429, 503): |
| 619 | return [], f"HTTP {e.code}" |
| 620 | # 会话预热:访问同站首页获取会话 Cookie,2 秒后重试一次 |
| 621 | home = urllib.parse.urlparse(req_host_url) |
| 622 | home_url = f"{home.scheme}://{home.netloc}/" |
| 623 | try: |
| 624 | http_get(home_url, args.timeout, opener) |
| 625 | time.sleep(2) |
| 626 | page = _do_request(engine_id, fetch_tpl, post_cfg, query, q, args, opener) |
| 627 | except urllib.error.HTTPError as e2: |
| 628 | return [], f"HTTP {e2.code}(会话预热后仍被拦截,建议换引擎或改用链接模式)" |
| 629 | except (urllib.error.URLError, TimeoutError, OSError) as e2: |
| 630 | return [], f"HTTP {e.code} 后会话预热失败({type(e2).__name__}),建议换引擎" |
| 631 | except (urllib.error.URLError, TimeoutError, OSError) as e: |
| 632 | return [], f"网络不可达/超时({type(e).__name__};该引擎可能需国际网络)" |
| 633 | |
| 634 | low = page.lower() |
| 635 | if any(k in low for k in ("captcha", "/sorry/", "验证", "人机校验")) and len(low) < 6000: |
| 636 | return [], "出现验证码/人机校验,已按规范停止抓取" |
| 637 | results = extract_results(engine_id, page, args.limit) |
| 638 | if not results: |
| 639 | return [], "页面已返回但未解析到结果(结构变化或地区重定向)" |
| 640 | if engine_id == "duckduckgo": |
| 641 | snippets = extract_ddg_snippets(page) |
| 642 | for i, r in enumerate(results): |
| 643 | if i < len(snippets): |
| 644 | r["snippet"] = snippets[i] |
| 645 | return results, None |
| 646 | |
| 647 | |
| 648 | def merge_results(per_engine): |
| 649 | """跨引擎合并去重,多源命中的结果排名靠前。""" |
| 650 | merged = {} |
| 651 | order = [] |
| 652 | for engine_id, results in per_engine: |
| 653 | for rank, r in enumerate(results): |
| 654 | key = normalize_url(r["url"]) |
| 655 | if key not in merged: |
| 656 | merged[key] = { |
| 657 | "title": r["title"], "url": r["url"], |
| 658 | "engines": [engine_id], "best_rank": rank, |
| 659 | "snippet": r.get("snippet", ""), |
| 660 | } |
| 661 | order.append(key) |
| 662 | else: |
| 663 | if engine_id not in merged[key]["engines"]: |
| 664 | merged[key]["engines"].append(engine_id) |
| 665 | merged[key]["best_rank"] = min(merged[key]["best_rank"], rank) |
| 666 | if not merged[key]["snippet"] and r.get("snippet"): |
| 667 | merged[key]["snippet"] = r["snippet"] |
| 668 | items = [merged[k] for k in order] |
| 669 | items.sort(key=lambda x: (-len(x["engines"]), x["best_rank"])) |
| 670 | return items |
| 671 | |
| 672 | |
| 673 | # ------------------------- 输出 ------------------------- |
| 674 | |
| 675 | def engine_label(eid): |
| 676 | if eid in ENGINES: |
| 677 | return ENGINES[eid]["name"] |
| 678 | return VERTICAL_ENGINES[eid][0] |
| 679 | |
| 680 | |
| 681 | def render_markdown(query, engine_ids, attempted, failures, merged, link_urls, fetched): |
| 682 | now = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 683 | lines = ["# 多引擎搜索报告", "", |
| 684 | f"- 查询词:`{query}`", f"- 生成时间:{now}", |
| 685 | f"- 模式:{'抓取聚合' if fetched else '链接生成(未发起网络请求)'}"] |
| 686 | ok = [f"{engine_label(e)}({e})" for e, ok_ in attempted if ok_] |
| 687 | bad = [f"{engine_label(e)}({e}): {reason}" for e, reason in failures] |
| 688 | lines.append(f"- 成功引擎:{', '.join(ok) if ok else '无'}") |
| 689 | if bad: |
| 690 | lines.append(f"- 失败引擎:{'; '.join(bad)}") |
| 691 | lines.append("") |
| 692 | if fetched: |
| 693 | lines.append(f"## 去重后结果(共 {len(merged)} 条,多源命中优先)") |
| 694 | for i, r in enumerate(merged, 1): |
| 695 | host = urllib.parse.urlparse(r["url"]).netloc |
| 696 | src = ", ".join(engine_label(e) for e in r["engines"]) |
| 697 | lines.append(f"{i}. **{r['title']} — {host}**") |
| 698 | lines.append(f" - 链接:{r['url']}") |
| 699 | lines.append(f" - 来源:{src}") |
| 700 | if r.get("snippet"): |
| 701 | lines.append(f" - 摘要:{r['snippet'][:200]}") |
| 702 | lines.append("") |
| 703 | lines.append("## 各引擎搜索链接(点击即可在浏览器查看完整结果)") |
| 704 | lines.append("| 引擎 | 链接 |") |
| 705 | lines.append("|---|---|") |
| 706 | for eid in engine_ids: |
| 707 | lines.append(f"| {engine_label(eid)} | {link_urls[eid]} |") |
| 708 | lines.append("") |
| 709 | return "\n".join(lines) |
| 710 | |
| 711 | |
| 712 | def render_json(query, attempted, failures, merged, link_urls, fetched): |
| 713 | return { |
| 714 | "query": query, |
| 715 | "mode": "fetch" if fetched else "links", |
| 716 | "searched_at": _dt.datetime.now().isoformat(timespec="seconds"), |
| 717 | "engines_ok": [e for e, ok_ in attempted if ok_], |
| 718 | "engines_failed": [{"engine": e, "reason": why} for e, why in failures], |
| 719 | "result_count": len(merged), |
| 720 | "results": [ |
| 721 | {"rank": i, "title": r["title"], "url": r["url"], |
| 722 | "engines": r["engines"], "snippet": r.get("snippet", "")} |
| 723 | for i, r in enumerate(merged, 1) |
| 724 | ], |
| 725 | "search_links": link_urls, |
| 726 | } |
| 727 | |
| 728 | |
| 729 | # ------------------------- CLI ------------------------- |
| 730 | |
| 731 | def resolve_engine_ids(args): |
| 732 | all_cn = [e for e, m in ENGINES.items() if m["group"] == "cn"] |
| 733 | all_global = [e for e, m in ENGINES.items() if m["group"] == "global"] |
| 734 | if args.all: |
| 735 | engine_ids = list(ENGINES.keys()) |
| 736 | elif args.cn: |
| 737 | engine_ids = all_cn |
| 738 | elif args.global_: |
| 739 | engine_ids = all_global |
| 740 | elif args.engines: |
| 741 | engine_ids = [e.strip() for e in args.engines.split(",") if e.strip()] |
| 742 | else: |
| 743 | engine_ids = CN_DEFAULT |
| 744 | if args.vertical: |
| 745 | engine_ids += [v.strip() for v in args.vertical.split(",") if v.strip()] |
| 746 | unknown = [e for e in engine_ids if e not in ENGINES and e not in VERTICAL_ENGINES] |
| 747 | if unknown: |
| 748 | sys.exit(f"未知引擎: {', '.join(unknown)};用 --list-engines 查看全部引擎") |
| 749 | # 链接模式允许 wolframalpha;抓取模式它无结果解析 |
| 750 | return engine_ids |
| 751 | |
| 752 | |
| 753 | def main(argv=None): |
| 754 | parser = argparse.ArgumentParser( |
| 755 | description="多搜索引擎聚合检索(零依赖,支持链接模式与抓取模式)") |
| 756 | parser.add_argument("query", nargs="?", help="搜索关键词(可用 site:/filetype: 等操作符)") |
| 757 | parser.add_argument("-e", "--engines", help="引擎 id 逗号分隔,如 bing-cn,baidu,duckduckgo") |
| 758 | parser.add_argument("--cn", action="store_true", help="使用全部 7 个国内引擎") |
| 759 | parser.add_argument("--global", dest="global_", action="store_true", help="使用全部 9 个国际引擎") |
| 760 | parser.add_argument("--all", action="store_true", help="使用全部 16 个引擎") |
| 761 | parser.add_argument("--vertical", help="追加垂直站点:github,zhihu,bilibili,scholar 等") |
| 762 | parser.add_argument("--time", choices=list(TIME_CODES), help="时间范围 h/d/w/m/y(google/sogou/ddg 生效)") |
| 763 | parser.add_argument("--fetch", action="store_true", help="抓取搜索页并提取结果(默认仅生成链接)") |
| 764 | parser.add_argument("--limit", type=int, default=8, help="每个引擎最多提取条数,默认 8") |
| 765 | parser.add_argument("--delay", type=float, default=1.5, help="抓取请求间隔秒数,默认 1.5") |
| 766 | parser.add_argument("--timeout", type=float, default=10.0, help="单请求超时秒数,默认 10") |
| 767 | parser.add_argument("--json", action="store_true", help="输出 JSON 而非 Markdown") |
| 768 | parser.add_argument("--output", help="将报告保存到指定文件(默认只打印到标准输出)") |
| 769 | parser.add_argument("--list-engines", action="store_true", help="列出全部引擎后退出") |
| 770 | args = parser.parse_args(argv) |
| 771 | |
| 772 | if args.list_engines: |
| 773 | print("== 16 个核心搜索引擎 ==") |
| 774 | for eid, m in ENGINES.items(): |
| 775 | tag = "国内" if m["group"] == "cn" else "国际" |
| 776 | net = "大陆直连" if m["access"] == "direct" else "需国际网络" |
| 777 | print(f" {eid:13s} [{tag}|{net}|反爬{m['antibot']}] {m['name']}:{m['best']}") |
| 778 | print("\n== 垂直站点(通过 --vertical 追加)==") |
| 779 | for eid, (name, _) in VERTICAL_ENGINES.items(): |
| 780 | print(f" {eid:13s} {name}") |
| 781 | print("\n默认国内组合:" + ",".join(CN_DEFAULT)) |
| 782 | print("默认国际组合:" + ",".join(GLOBAL_DEFAULT)) |
| 783 | return 0 |
| 784 | |
| 785 | if not args.query or not args.query.strip(): |
| 786 | parser.error("查询词为空(仅空格也视为空),请提供有效关键词") |
| 787 | if args.limit < 1: |
| 788 | parser.error("--limit 必须为正整数(1-50),当前为 %s" % args.limit) |
| 789 | if args.timeout <= 0: |
| 790 | parser.error("--timeout 必须大于 0(秒),当前为 %s" % args.timeout) |
| 791 | if args.delay < 0: |
| 792 | parser.error("--delay 不能为负数,当前为 %s" % args.delay) |
| 793 | if len(urllib.parse.quote(args.query, safe="")) > 1800: |
| 794 | print("提示:查询词编码后超过 1800 字符,搜索引擎可能截断,建议拆分为多次检索", |
| 795 | file=sys.stderr) |
| 796 | |
| 797 | engine_ids = resolve_engine_ids(args) |
| 798 | link_urls = {eid: build_url(eid, args.query, args.time) for eid in engine_ids} |
| 799 | |
| 800 | attempted, failures, per_engine = [], [], [] |
| 801 | merged = [] |
| 802 | if args.fetch: |
| 803 | for i, eid in enumerate(engine_ids): |
| 804 | if ENGINES.get(eid, {}).get("extract", True) is False: |
| 805 | failures.append((eid, "该引擎为计算型知识入口,不适用网页结果解析,请直接点击链接")) |
| 806 | attempted.append((eid, False)) |
| 807 | continue |
| 808 | results, err = search_one(eid, args.query, args) |
| 809 | if err: |
| 810 | failures.append((eid, err)) |
| 811 | attempted.append((eid, False)) |
| 812 | else: |
| 813 | attempted.append((eid, True)) |
| 814 | per_engine.append((eid, results)) |
| 815 | if i < len(engine_ids) - 1: |
| 816 | time.sleep(max(args.delay, 1.0)) |
| 817 | merged = merge_results(per_engine) |
| 818 | |
| 819 | if args.json: |
| 820 | report = json.dumps(render_json(args.query, attempted, failures, merged, |
| 821 | link_urls, args.fetch), ensure_ascii=False, indent=2) |
| 822 | else: |
| 823 | report = render_markdown(args.query, engine_ids, attempted, failures, merged, |
| 824 | link_urls, args.fetch) |
| 825 | if args.output: |
| 826 | try: |
| 827 | with open(args.output, "w", encoding="utf-8") as f: |
| 828 | f.write(report) |
| 829 | except OSError as exc: |
| 830 | sys.exit(f"无法写入输出文件 {args.output}:{exc}(请检查目录是否存在、是否有写权限)") |
| 831 | print(f"报告已保存:{args.output}", file=sys.stderr) |
| 832 | else: |
| 833 | print(report) |
| 834 | return 0 if (not args.fetch or not failures or merged) else 1 |
| 835 | |
| 836 | |
| 837 | if __name__ == "__main__": |
| 838 | sys.exit(main()) |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

