test_steam_market_proxy.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #!/usr/bin/env python3
  2. """
  3. 测试 Steam Market render 接口在直连与代理下的可达性。
  4. 默认测试 URL:
  5. https://steamcommunity.com/market/listings/730/P90%20%7C%20Sand%20Spray%20%28Minimal%20Wear%29/render/?query=&start=0&count=10&country=US&language=schinese&currency=1
  6. 默认代理:
  7. http://192.154.231.161:10609
  8. """
  9. from __future__ import annotations
  10. import argparse
  11. import json
  12. import ssl
  13. import sys
  14. import time
  15. from typing import Any, Dict, Optional
  16. from urllib.error import HTTPError, URLError
  17. from urllib.request import HTTPSHandler, ProxyHandler, Request, build_opener
  18. DEFAULT_URL = (
  19. "https://steamcommunity.com/market/listings/730/"
  20. "P90%20%7C%20Sand%20Spray%20%28Minimal%20Wear%29/"
  21. "render/?query=&start=0&count=10&country=US&language=schinese&currency=1"
  22. )
  23. DEFAULT_PROXY = "http://192.154.231.161:10795"
  24. def fetch(url: str, timeout: int, proxy: Optional[str], verify_ssl: bool = True) -> Dict[str, Any]:
  25. handlers = []
  26. if proxy:
  27. handlers.append(ProxyHandler({"http": proxy, "https": proxy}))
  28. if not verify_ssl:
  29. # Only for temporary connectivity testing.
  30. handlers.append(HTTPSHandler(context=ssl._create_unverified_context()))
  31. opener = build_opener(*handlers)
  32. req = Request(
  33. url=url,
  34. headers={
  35. "User-Agent": "Mozilla/5.0 (compatible; steam-proxy-check/1.0)",
  36. "Accept": "application/json,text/plain,*/*",
  37. "Connection": "close",
  38. },
  39. method="GET",
  40. )
  41. start = time.perf_counter()
  42. try:
  43. with opener.open(req, timeout=timeout) as resp:
  44. status = getattr(resp, "status", None) or resp.getcode()
  45. body_bytes = resp.read()
  46. elapsed = (time.perf_counter() - start) * 1000
  47. text = body_bytes.decode("utf-8", errors="replace")
  48. content_type = resp.headers.get("Content-Type", "")
  49. return {
  50. "ok": True,
  51. "status": status,
  52. "elapsed_ms": round(elapsed, 2),
  53. "content_type": content_type,
  54. "body_len": len(body_bytes),
  55. "body_preview": text[:400],
  56. }
  57. except HTTPError as e:
  58. elapsed = (time.perf_counter() - start) * 1000
  59. err_body = ""
  60. try:
  61. err_body = e.read().decode("utf-8", errors="replace")[:400]
  62. except Exception:
  63. err_body = ""
  64. return {
  65. "ok": False,
  66. "status": e.code,
  67. "elapsed_ms": round(elapsed, 2),
  68. "error": f"HTTPError: {e}",
  69. "body_preview": err_body,
  70. }
  71. except URLError as e:
  72. elapsed = (time.perf_counter() - start) * 1000
  73. return {
  74. "ok": False,
  75. "status": None,
  76. "elapsed_ms": round(elapsed, 2),
  77. "error": f"URLError: {e}",
  78. }
  79. except Exception as e:
  80. elapsed = (time.perf_counter() - start) * 1000
  81. return {
  82. "ok": False,
  83. "status": None,
  84. "elapsed_ms": round(elapsed, 2),
  85. "error": f"{type(e).__name__}: {e}",
  86. }
  87. def main() -> int:
  88. parser = argparse.ArgumentParser(description="Test steam market render URL with/without proxy")
  89. parser.add_argument("--url", default=DEFAULT_URL, help="Target URL")
  90. parser.add_argument("--proxy", default=DEFAULT_PROXY, help="HTTP/HTTPS proxy URL")
  91. parser.add_argument("--timeout", type=int, default=20, help="Timeout seconds")
  92. parser.add_argument(
  93. "--insecure",
  94. action="store_true",
  95. help="Disable SSL certificate verification (testing only)",
  96. )
  97. parser.add_argument("--skip-direct", action="store_true", help="Skip direct test")
  98. args = parser.parse_args()
  99. print("=== Steam Market Proxy Test ===")
  100. print(f"URL : {args.url}")
  101. print(f"Proxy : {args.proxy}")
  102. print(f"Timeout: {args.timeout}s")
  103. print(f"SSL verify: {not args.insecure}")
  104. print()
  105. if not args.skip_direct:
  106. print("[1/2] Direct request (no proxy)")
  107. direct = fetch(args.url, args.timeout, proxy=None, verify_ssl=not args.insecure)
  108. print(json.dumps(direct, ensure_ascii=False, indent=2))
  109. print()
  110. else:
  111. direct = None
  112. print("[2/2] Proxy request")
  113. via_proxy = fetch(args.url, args.timeout, proxy=args.proxy, verify_ssl=not args.insecure)
  114. print(json.dumps(via_proxy, ensure_ascii=False, indent=2))
  115. print()
  116. if direct is not None:
  117. print("=== Summary ===")
  118. print(f"Direct ok: {direct.get('ok')} | status: {direct.get('status')}")
  119. print(f"Proxy ok: {via_proxy.get('ok')} | status: {via_proxy.get('status')}")
  120. else:
  121. print("=== Summary ===")
  122. print(f"Proxy ok: {via_proxy.get('ok')} | status: {via_proxy.get('status')}")
  123. return 0
  124. if __name__ == "__main__":
  125. sys.exit(main())