proxy-scraper-cli 1.19.0__tar.gz → 1.20.0__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.
Files changed (120) hide show
  1. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/PKG-INFO +16 -1
  2. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/README.md +15 -0
  3. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxy_scraper_cli.egg-info/PKG-INFO +16 -1
  4. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/__init__.py +1 -1
  5. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/agent.py +31 -8
  6. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/api.py +77 -3
  7. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_rotator.py +92 -0
  8. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/LICENSE +0 -0
  9. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxy_scraper_cli.egg-info/SOURCES.txt +0 -0
  10. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxy_scraper_cli.egg-info/dependency_links.txt +0 -0
  11. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxy_scraper_cli.egg-info/entry_points.txt +0 -0
  12. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxy_scraper_cli.egg-info/requires.txt +0 -0
  13. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxy_scraper_cli.egg-info/top_level.txt +0 -0
  14. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/__main__.py +0 -0
  15. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/action.py +0 -0
  16. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/app.py +0 -0
  17. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/asndb.py +0 -0
  18. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/blocklist.py +0 -0
  19. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/charts.py +0 -0
  20. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/checker.py +0 -0
  21. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/cli.py +0 -0
  22. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/compat.py +0 -0
  23. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/completion.py +0 -0
  24. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/exporters.py +0 -0
  25. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/fetchcache.py +0 -0
  26. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/geo.py +0 -0
  27. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/geodb.py +0 -0
  28. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/handshake.py +0 -0
  29. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/history.py +0 -0
  30. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/judges.py +0 -0
  31. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/mcp_entry.py +0 -0
  32. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/mcp_server.py +0 -0
  33. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/netio.py +0 -0
  34. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/options.py +0 -0
  35. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/output.py +0 -0
  36. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/pages.py +0 -0
  37. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/parsing.py +0 -0
  38. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/paths.py +0 -0
  39. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/pipeline.py +0 -0
  40. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/preferences.py +0 -0
  41. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/proxypages.py +0 -0
  42. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/publish.py +0 -0
  43. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ranking.py +0 -0
  44. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/report.py +0 -0
  45. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/runsteps.py +0 -0
  46. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/server/__init__.py +0 -0
  47. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/server/core.py +0 -0
  48. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/server/http.py +0 -0
  49. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/server/pool.py +0 -0
  50. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/server/socks.py +0 -0
  51. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/server/status.py +0 -0
  52. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/server/upstream.py +0 -0
  53. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/site/apple-touch-icon.png +0 -0
  54. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/site/googleaac1161b7853c5b5.html +0 -0
  55. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/site/index.html +0 -0
  56. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/site/logo.png +0 -0
  57. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/site/og.png +0 -0
  58. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/sites.py +0 -0
  59. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/sources.json +0 -0
  60. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/sources.py +0 -0
  61. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/speed.py +0 -0
  62. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/targets.py +0 -0
  63. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ui/__init__.py +0 -0
  64. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ui/dashboard.py +0 -0
  65. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ui/keys.py +0 -0
  66. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ui/report.py +0 -0
  67. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ui/serve.py +0 -0
  68. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ui/widgets.py +0 -0
  69. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/proxyscraper/ui/wizard.py +0 -0
  70. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/pyproject.toml +0 -0
  71. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/setup.cfg +0 -0
  72. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_action.py +0 -0
  73. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_agent.py +0 -0
  74. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_api.py +0 -0
  75. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_app.py +0 -0
  76. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_asndb.py +0 -0
  77. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_auth.py +0 -0
  78. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_blocklist.py +0 -0
  79. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_charts.py +0 -0
  80. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_checker.py +0 -0
  81. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_compat.py +0 -0
  82. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_completion.py +0 -0
  83. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_discovery_growth.py +0 -0
  84. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_exporters.py +0 -0
  85. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_fetchcache.py +0 -0
  86. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_geodb.py +0 -0
  87. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_judges.py +0 -0
  88. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_learning.py +0 -0
  89. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_live_api.py +0 -0
  90. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_mcp_server.py +0 -0
  91. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_mine_sources.py +0 -0
  92. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_options.py +0 -0
  93. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_output_stdout.py +0 -0
  94. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_packaging.py +0 -0
  95. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_pages.py +0 -0
  96. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_parsing.py +0 -0
  97. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_parsing_fuzz.py +0 -0
  98. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_paths.py +0 -0
  99. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_pick.py +0 -0
  100. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_pipeline.py +0 -0
  101. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_proxy_pages.py +0 -0
  102. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_proxy_sources.py +0 -0
  103. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_publish.py +0 -0
  104. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_report.py +0 -0
  105. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_robustness.py +0 -0
  106. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_serve_password.py +0 -0
  107. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_serve_refill.py +0 -0
  108. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_serve_v2.py +0 -0
  109. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_server.py +0 -0
  110. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_server_closed_writer.py +0 -0
  111. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_server_fixes.py +0 -0
  112. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_sites.py +0 -0
  113. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_sources_json.py +0 -0
  114. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_speed.py +0 -0
  115. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_speed_ranking.py +0 -0
  116. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_tamper.py +0 -0
  117. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_targets.py +0 -0
  118. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_ui.py +0 -0
  119. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_uptime.py +0 -0
  120. {proxy_scraper_cli-1.19.0 → proxy_scraper_cli-1.20.0}/tests/test_wizard.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: proxy-scraper-cli
3
- Version: 1.19.0
3
+ Version: 1.20.0
4
4
  Summary: Finds free HTTP, SOCKS4 and SOCKS5 proxies that actually work: 700+ sources, real checks, honeypot filtering and a rotating local proxy server.
5
5
  Author: Maximilian Feix
6
6
  License-Expression: MIT
@@ -456,6 +456,21 @@ with ProxyRotator(country="DE") as rotator:
456
456
 
457
457
  Usually a few seconds; when many proxies in a row are down it can take a minute (`timeout=` is per attempt). There's `aget()` with `async with` for asyncio code.
458
458
 
459
+ Already using requests, httpx, Playwright or Scrapy? `proxy_url()` gives you one local proxy address that rotates behind the scenes – every connection goes out through another proxy from the list, best first, dead ones skipped:
460
+
461
+ ```python
462
+ import requests
463
+ from proxyscraper import ProxyRotator
464
+
465
+ with ProxyRotator(country="DE") as rotator:
466
+ proxy = rotator.proxy_url() # http://country-de:…@127.0.0.1:…
467
+ requests.get("https://api.ipify.org", proxies={"http": proxy, "https": proxy})
468
+ # httpx.Client(proxy=proxy) · scrapy: meta={"proxy": proxy} · curl -x "$proxy"
469
+ # Playwright wants the login apart: chromium.launch(proxy=rotator.playwright_proxy())
470
+ ```
471
+
472
+ It runs on 127.0.0.1 with a random password, takes over each new hourly list by itself and stops with the `with` block.
473
+
459
474
  <a id="proxy-server"></a>
460
475
 
461
476
  ## Rotating proxy server
@@ -415,6 +415,21 @@ with ProxyRotator(country="DE") as rotator:
415
415
 
416
416
  Usually a few seconds; when many proxies in a row are down it can take a minute (`timeout=` is per attempt). There's `aget()` with `async with` for asyncio code.
417
417
 
418
+ Already using requests, httpx, Playwright or Scrapy? `proxy_url()` gives you one local proxy address that rotates behind the scenes – every connection goes out through another proxy from the list, best first, dead ones skipped:
419
+
420
+ ```python
421
+ import requests
422
+ from proxyscraper import ProxyRotator
423
+
424
+ with ProxyRotator(country="DE") as rotator:
425
+ proxy = rotator.proxy_url() # http://country-de:…@127.0.0.1:…
426
+ requests.get("https://api.ipify.org", proxies={"http": proxy, "https": proxy})
427
+ # httpx.Client(proxy=proxy) · scrapy: meta={"proxy": proxy} · curl -x "$proxy"
428
+ # Playwright wants the login apart: chromium.launch(proxy=rotator.playwright_proxy())
429
+ ```
430
+
431
+ It runs on 127.0.0.1 with a random password, takes over each new hourly list by itself and stops with the `with` block.
432
+
418
433
  <a id="proxy-server"></a>
419
434
 
420
435
  ## Rotating proxy server
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: proxy-scraper-cli
3
- Version: 1.19.0
3
+ Version: 1.20.0
4
4
  Summary: Finds free HTTP, SOCKS4 and SOCKS5 proxies that actually work: 700+ sources, real checks, honeypot filtering and a rotating local proxy server.
5
5
  Author: Maximilian Feix
6
6
  License-Expression: MIT
@@ -456,6 +456,21 @@ with ProxyRotator(country="DE") as rotator:
456
456
 
457
457
  Usually a few seconds; when many proxies in a row are down it can take a minute (`timeout=` is per attempt). There's `aget()` with `async with` for asyncio code.
458
458
 
459
+ Already using requests, httpx, Playwright or Scrapy? `proxy_url()` gives you one local proxy address that rotates behind the scenes – every connection goes out through another proxy from the list, best first, dead ones skipped:
460
+
461
+ ```python
462
+ import requests
463
+ from proxyscraper import ProxyRotator
464
+
465
+ with ProxyRotator(country="DE") as rotator:
466
+ proxy = rotator.proxy_url() # http://country-de:…@127.0.0.1:…
467
+ requests.get("https://api.ipify.org", proxies={"http": proxy, "https": proxy})
468
+ # httpx.Client(proxy=proxy) · scrapy: meta={"proxy": proxy} · curl -x "$proxy"
469
+ # Playwright wants the login apart: chromium.launch(proxy=rotator.playwright_proxy())
470
+ ```
471
+
472
+ It runs on 127.0.0.1 with a random password, takes over each new hourly list by itself and stops with the `with` block.
473
+
459
474
  <a id="proxy-server"></a>
460
475
 
461
476
  ## Rotating proxy server
@@ -1,7 +1,7 @@
1
1
  """proxy-scraper: collects public HTTP/SOCKS4/SOCKS5 proxies from hundreds of sources, checks them
2
2
  in parallel with its own protocol handshakes and learns which sources deliver good proxies."""
3
3
 
4
- __version__ = "1.19.0"
4
+ __version__ = "1.20.0"
5
5
 
6
6
 
7
7
  def __getattr__(name):
@@ -458,6 +458,22 @@ def _to_text(body: bytes, headers, content_type: str, raw_html: bool) -> str:
458
458
  return text if raw_html or "html" not in content_type.lower() else html_to_text(text)
459
459
 
460
460
 
461
+ def _require_match(live: LiveList, protocol: str, countries: List[str], tls: bool) -> None:
462
+ if not any(True for _ in matching(live.rows, protocol, countries, https_only=tls, run_hours=live.run_hours)):
463
+ what = " ".join(x for x in (countries[0] if countries else "", "" if protocol == "any" else protocol,
464
+ "HTTPS-capable" if tls else "") if x)
465
+ raise AgentError(f"No {what} proxy in the live list right now."
466
+ + (shortage_note(live.rows, 1, 0, countries) or ""))
467
+
468
+
469
+ def _wishes(protocol: str, countries: List[str]) -> List[str]:
470
+ """What the rotating server reads from the proxy login: country-de, type-socks5."""
471
+ wishes = [f"country-{countries[0].lower()}"] if countries else []
472
+ if protocol != "any":
473
+ wishes.append(f"type-{protocol}")
474
+ return wishes
475
+
476
+
461
477
  class PageFetcher:
462
478
  """Loads pages through the rotating server of this package, running on 127.0.0.1 with a random password:
463
479
  the same failover as `--serve`, and HTTPS only through proxies that passed the verified-TLS test.
@@ -503,6 +519,19 @@ class PageFetcher:
503
519
  self._list_id = list_id
504
520
  return live
505
521
 
522
+ async def local_proxy(self, protocol: str = "any", country: str = "") -> str:
523
+ """The URL of the rotating server behind this fetcher, with the login, for any HTTP client:
524
+ http://country-de:<password>@127.0.0.1:<port>. Every connection through it gets a proxy of its own."""
525
+ protocol = _check_protocol(protocol)
526
+ countries = normalize_countries([country] if country else [])
527
+ _require_match(await self._ready(), protocol, countries, tls=False)
528
+ user = "-".join(_wishes(protocol, countries)) or "any"
529
+ return f"http://{user}:{self._password}@127.0.0.1:{self.server.port}"
530
+
531
+ async def refresh(self) -> None:
532
+ """Take over a new run's list, if there is one (fetch does that by itself)."""
533
+ await self._ready()
534
+
506
535
  async def fetch(self, url: str, protocol: str = "any", country: str = "", max_chars: int = 20000,
507
536
  raw_html: bool = False, progress: Optional[Progress] = None, tick: float = 5.0,
508
537
  with_body: bool = False) -> dict:
@@ -511,15 +540,9 @@ class PageFetcher:
511
540
  countries = normalize_countries([country] if country else [])
512
541
  live = await self._ready()
513
542
  tls = urlsplit(url).scheme == "https"
514
- if not any(True for _ in matching(live.rows, protocol, countries, https_only=tls, run_hours=live.run_hours)):
515
- what = " ".join(x for x in (countries[0] if countries else "", "" if protocol == "any" else protocol,
516
- "HTTPS-capable" if tls else "") if x)
517
- raise AgentError(f"No {what} proxy in the live list right now."
518
- + (shortage_note(live.rows, 1, 0, countries) or ""))
543
+ _require_match(live, protocol, countries, tls)
519
544
  session = secrets.token_hex(6)
520
- wishes = [f"country-{countries[0].lower()}"] if countries else []
521
- if protocol != "any":
522
- wishes.append(f"type-{protocol}")
545
+ wishes = _wishes(protocol, countries)
523
546
  pool, port = self.server.pool, self.server.port
524
547
  started = time.monotonic()
525
548
  result, faults, suspects = None, [], []
@@ -27,12 +27,14 @@ import asyncio
27
27
  import contextlib
28
28
  import email.message
29
29
  import io
30
+ import logging
30
31
  import os
31
32
  import re
32
33
  import tempfile
33
34
  import threading
34
35
  from dataclasses import dataclass, field
35
36
  from typing import Dict, Iterable, List, Optional, Tuple
37
+ from urllib.parse import urlsplit
36
38
 
37
39
  from rich.console import Console
38
40
 
@@ -42,6 +44,8 @@ from .parsing import PROXY_TYPES
42
44
  from .targets import parse_target
43
45
  from .ui import widgets
44
46
 
47
+ log = logging.getLogger(__name__)
48
+
45
49
  __all__ = [
46
50
  "CheckResult",
47
51
  "LiveProxy",
@@ -309,6 +313,15 @@ class ProxyResponse:
309
313
  raise ConnectionError(f"the body from {self.final_url} was cut off at 2 MB")
310
314
 
311
315
 
316
+ REFRESH_SECONDS = 300 # proxy_url(): how often the pool behind it looks for a new run's list
317
+
318
+
319
+ def _playwright(url: str) -> Dict[str, str]:
320
+ parts = urlsplit(url)
321
+ return {"server": f"{parts.scheme}://{parts.hostname}:{parts.port}", "username": parts.username or "",
322
+ "password": parts.password or ""}
323
+
324
+
312
325
  class ProxyRotator:
313
326
  """Loads URLs through proxies from the hourly list and switches to the next one when a proxy fails –
314
327
  the loop every scraper writes by hand. HTTPS only through proxies with verified TLS.
@@ -330,6 +343,7 @@ class ProxyRotator:
330
343
  self._loop: Optional[asyncio.AbstractEventLoop] = None # the sync API's own loop, in a thread
331
344
  self._thread: Optional[threading.Thread] = None
332
345
  self._start_lock = threading.Lock()
346
+ self._refresher: Optional[asyncio.Task] = None
333
347
 
334
348
  def _use(self, mode: str) -> None:
335
349
  if self._mode is None:
@@ -367,7 +381,43 @@ class ProxyRotator:
367
381
  proxy_country=page["proxy_country"], elapsed_ms=page["elapsed_ms"],
368
382
  truncated=page["body_truncated"])
369
383
 
384
+ async def aproxy_url(self) -> str:
385
+ self._use("async")
386
+ return await self._proxy_url()
387
+
388
+ async def _proxy_url(self) -> str:
389
+ from .agent import AgentError
390
+
391
+ if self._fetcher is None:
392
+ self._fetcher = self._make_fetcher()
393
+ try:
394
+ url = await self._fetcher.local_proxy(self.protocol, self.country)
395
+ except AgentError as e:
396
+ raise ConnectionError(str(e)) from None
397
+ if self._refresher is None: # nobody calls get() on this path, so the pool refreshes by itself
398
+ self._refresher = asyncio.ensure_future(self._keep_fresh())
399
+ return url
400
+
401
+ async def aplaywright_proxy(self) -> Dict[str, str]:
402
+ self._use("async")
403
+ return _playwright(await self._proxy_url())
404
+
405
+ async def _keep_fresh(self) -> None:
406
+ from .agent import AgentError
407
+
408
+ while True:
409
+ await asyncio.sleep(REFRESH_SECONDS)
410
+ try:
411
+ await self._fetcher.refresh()
412
+ except AgentError:
413
+ pass # GitHub not reachable right now: the pool keeps what it has, next try later
414
+ except Exception as e: # a broken list must not end the refreshing for good
415
+ log.warning("proxy-scraper: could not refresh the proxy list: %s", e)
416
+
370
417
  async def aclose(self) -> None:
418
+ if self._refresher is not None:
419
+ self._refresher.cancel()
420
+ self._refresher = None
371
421
  if self._fetcher is not None:
372
422
  await self._fetcher.close()
373
423
  self._fetcher = None
@@ -380,13 +430,37 @@ class ProxyRotator:
380
430
 
381
431
  # sync: one event loop in a background thread keeps the proxy server alive between calls
382
432
  def get(self, url: str) -> ProxyResponse:
383
- with self._start_lock: # several threads calling get() at once still share one loop
384
- self._use("sync")
433
+ return self._run_sync(self._aget(url))
434
+
435
+ def _run_sync(self, coro):
436
+ with self._start_lock: # several threads calling at once still share one loop
437
+ try:
438
+ self._use("sync")
439
+ except RuntimeError:
440
+ coro.close()
441
+ raise
385
442
  if self._loop is None:
386
443
  self._loop = asyncio.new_event_loop()
387
444
  self._thread = threading.Thread(target=self._loop.run_forever, name="proxy-rotator", daemon=True)
388
445
  self._thread.start()
389
- return asyncio.run_coroutine_threadsafe(self._aget(url), self._loop).result()
446
+ return asyncio.run_coroutine_threadsafe(coro, self._loop).result()
447
+
448
+ def proxy_url(self) -> str:
449
+ """A local proxy URL for any library – requests, httpx, aiohttp, Playwright, Scrapy, curl:
450
+
451
+ with ProxyRotator(country="DE") as rotator:
452
+ proxy = rotator.proxy_url()
453
+ requests.get(url, proxies={"http": proxy, "https": proxy})
454
+
455
+ Every connection through it gets a proxy from the live list (best first, with failover), HTTPS only
456
+ through verified-TLS ones. It lives as long as the rotator and takes over each new run's list."""
457
+ return self._run_sync(self._proxy_url())
458
+
459
+ def playwright_proxy(self) -> Dict[str, str]:
460
+ """proxy_url() the way Playwright wants it – it ignores a login inside the server address:
461
+
462
+ browser = p.chromium.launch(proxy=rotator.playwright_proxy())"""
463
+ return _playwright(self.proxy_url())
390
464
 
391
465
  def close(self) -> None:
392
466
  with self._start_lock:
@@ -127,3 +127,95 @@ def test_mixing_sync_and_async_is_refused(monkeypatch):
127
127
  with pytest.raises(RuntimeError, match="async"):
128
128
  asyncio.run(rotator.aget("http://x/"))
129
129
  rotator.close()
130
+
131
+
132
+ def get_through(proxy_url: str, url: str):
133
+ """A plain GET through an HTTP proxy URL with a login, the way requests or httpx send it."""
134
+ import base64
135
+ import http.client
136
+ from urllib.parse import urlsplit
137
+
138
+ p = urlsplit(proxy_url)
139
+ login = base64.b64encode(f"{p.username}:{p.password}".encode()).decode()
140
+ conn = http.client.HTTPConnection(p.hostname, p.port, timeout=10)
141
+ conn.request("GET", url, headers={"Proxy-Authorization": f"Basic {login}"})
142
+ response = conn.getresponse()
143
+ return response.status, response.read()
144
+
145
+
146
+ def test_proxy_url_is_a_rotating_proxy_for_any_library():
147
+ loop = asyncio.new_event_loop()
148
+ target_srv, proxy_srv, port, rows = loop.run_until_complete(local_setup())
149
+ import threading
150
+ thread = threading.Thread(target=loop.run_forever, daemon=True)
151
+ thread.start()
152
+ try:
153
+ with ProxyRotator(_source=source_for(rows), _allow_private=True, timeout=5) as rotator:
154
+ url = rotator.proxy_url()
155
+ assert url.startswith("http://") and "@127.0.0.1:" in url
156
+ # the dead proxy is tried and skipped inside, the client just gets its page
157
+ assert get_through(url, f"http://127.0.0.1:{port}/ok") == (200, b"ok")
158
+ assert rotator.proxy_url() == url # the same server for the rotator's lifetime
159
+ finally:
160
+ loop.call_soon_threadsafe(target_srv.close)
161
+ loop.call_soon_threadsafe(proxy_srv.close)
162
+ loop.call_soon_threadsafe(loop.stop)
163
+
164
+
165
+ def test_proxy_url_carries_country_and_protocol_and_refuses_what_isnt_there():
166
+ async def go(**wishes):
167
+ rows = [row(1, country="DE", ptype="socks5")]
168
+ async with ProxyRotator(_source=source_for(rows), _allow_private=True, **wishes) as rotator:
169
+ return await rotator.aproxy_url()
170
+ assert "//country-de-type-socks5:" in asyncio.run(go(country="de", protocol="socks5"))
171
+
172
+ async def for_playwright():
173
+ async with ProxyRotator(_source=source_for([row(1)]), _allow_private=True) as rotator:
174
+ return await rotator.aproxy_url(), await rotator.aplaywright_proxy()
175
+ url, settings = asyncio.run(for_playwright())
176
+ # Playwright ignores a login inside "server": it wants the parts on their own
177
+ assert settings["server"] == "http://" + url.rsplit("@", 1)[1] and "@" not in settings["server"]
178
+ assert url == f"http://{settings['username']}:{settings['password']}@{settings['server'][7:]}"
179
+ with pytest.raises(ConnectionError, match="JP"):
180
+ asyncio.run(go(country="JP"))
181
+
182
+
183
+ def test_proxy_url_keeps_the_pool_fresh(monkeypatch):
184
+ from proxyscraper import api
185
+
186
+ monkeypatch.setattr(api, "REFRESH_SECONDS", 0.05)
187
+ runs = iter([agent.LiveList(rows=[row(1)], stats={**STATS, "updated": "run 1"}, loaded_at=0.0),
188
+ agent.LiveList(rows=[row(2)], stats={**STATS, "updated": "run 2"}, loaded_at=0.0)])
189
+
190
+ class Source: # the first call sees run 1, every later one run 2
191
+ current = None
192
+
193
+ async def get(self):
194
+ self.current = next(runs, self.current)
195
+ return self.current
196
+
197
+ async def go():
198
+ async with ProxyRotator(_source=Source(), _allow_private=True) as rotator:
199
+ await rotator.aproxy_url()
200
+ await asyncio.sleep(0.3)
201
+ return {e.result.proxy for e in rotator._fetcher.server.pool.entries}
202
+ assert asyncio.run(go()) == {row(2)["proxy"]}
203
+
204
+
205
+ def test_the_refresh_survives_a_surprise(monkeypatch):
206
+ from proxyscraper import api
207
+
208
+ monkeypatch.setattr(api, "REFRESH_SECONDS", 0.02)
209
+ calls = []
210
+
211
+ async def go():
212
+ async with ProxyRotator(_source=source_for([row(1)]), _allow_private=True) as rotator:
213
+ await rotator.aproxy_url()
214
+
215
+ async def broken():
216
+ calls.append(1)
217
+ raise KeyError("stats")
218
+ rotator._fetcher.refresh = broken
219
+ await asyncio.sleep(0.2)
220
+ asyncio.run(go())
221
+ assert len(calls) > 2 # kept trying after the first failure