google-browser-scraper 0.1.1__tar.gz → 0.1.2__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 (48) hide show
  1. {google_browser_scraper-0.1.1/src/google_browser_scraper.egg-info → google_browser_scraper-0.1.2}/PKG-INFO +5 -4
  2. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/README.md +4 -3
  3. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/pyproject.toml +1 -1
  4. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/__init__.py +1 -1
  5. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/hybrid.py +65 -0
  6. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/links.py +87 -2
  7. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/scraper.py +26 -3
  8. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2/src/google_browser_scraper.egg-info}/PKG-INFO +5 -4
  9. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_hybrid.py +59 -2
  10. google_browser_scraper-0.1.2/tests/test_links.py +273 -0
  11. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_scraper.py +14 -0
  12. google_browser_scraper-0.1.1/tests/test_links.py +0 -112
  13. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/LICENSE +0 -0
  14. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/MANIFEST.in +0 -0
  15. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/setup.cfg +0 -0
  16. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/__main__.py +0 -0
  17. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/browser.py +0 -0
  18. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/classify.py +0 -0
  19. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/cli.py +0 -0
  20. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/doctor.py +0 -0
  21. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/engines.py +0 -0
  22. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/mcp.py +0 -0
  23. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/output.py +0 -0
  24. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/parse.py +0 -0
  25. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/pool.py +0 -0
  26. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/proxy.py +0 -0
  27. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/quality.py +0 -0
  28. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/relay.py +0 -0
  29. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/server.py +0 -0
  30. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper/warmup.py +0 -0
  31. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper.egg-info/SOURCES.txt +0 -0
  32. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper.egg-info/dependency_links.txt +0 -0
  33. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper.egg-info/entry_points.txt +0 -0
  34. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper.egg-info/requires.txt +0 -0
  35. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/src/google_browser_scraper.egg-info/top_level.txt +0 -0
  36. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/fakegoogle.py +0 -0
  37. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/pages.py +0 -0
  38. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/stdio_mcp_child.py +0 -0
  39. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_browser_local.py +0 -0
  40. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_classify.py +0 -0
  41. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_cli_and_output.py +0 -0
  42. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_engines_local.py +0 -0
  43. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_parse.py +0 -0
  44. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_pool.py +0 -0
  45. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_proxy.py +0 -0
  46. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_relay.py +0 -0
  47. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_serve_and_mcp.py +0 -0
  48. {google_browser_scraper-0.1.1 → google_browser_scraper-0.1.2}/tests/test_warmup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: google-browser-scraper
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Google Search results from a real browser through your own sticky proxy, with captchas and blocks reported explicitly.
5
5
  Author: NodeMaven
6
6
  License: MIT
@@ -368,9 +368,10 @@ copies carrying the cache are refused on their first search, the rest of the
368
368
  run copies cookies only (`--no-clone-cache` does that from the start).
369
369
 
370
370
  **Result links.** Google wraps result links in encrypted `/goto` redirects.
371
- Each one is resolved with a small request through a separate short-lived proxy
372
- session, a few at a time, in the background while the browser goes on to the
373
- next query. Records still come out in the order each browser searched them.
371
+ Each one is resolved with a small request on the proxy IP the page came from,
372
+ with that page's cookies, in the background while the next query runs; a link
373
+ left over is tried through a separate short-lived proxy session. Records still
374
+ come out in the order each browser searched them.
374
375
 
375
376
  **Traffic.** Everything goes through a small local relay that counts bytes per
376
377
  host and blocks a large model download Chrome otherwise makes on every fresh
@@ -336,9 +336,10 @@ copies carrying the cache are refused on their first search, the rest of the
336
336
  run copies cookies only (`--no-clone-cache` does that from the start).
337
337
 
338
338
  **Result links.** Google wraps result links in encrypted `/goto` redirects.
339
- Each one is resolved with a small request through a separate short-lived proxy
340
- session, a few at a time, in the background while the browser goes on to the
341
- next query. Records still come out in the order each browser searched them.
339
+ Each one is resolved with a small request on the proxy IP the page came from,
340
+ with that page's cookies, in the background while the next query runs; a link
341
+ left over is tried through a separate short-lived proxy session. Records still
342
+ come out in the order each browser searched them.
342
343
 
343
344
  **Traffic.** Everything goes through a small local relay that counts bytes per
344
345
  host and blocks a large model download Chrome otherwise makes on every fresh
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "google-browser-scraper"
7
- version = "0.1.1"
7
+ version = "0.1.2"
8
8
  description = "Google Search results from a real browser through your own sticky proxy, with captchas and blocks reported explicitly."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -7,7 +7,7 @@ for record in Scraper(proxy, Settings(pages=2)).run(["best running shoes"]):
7
7
  print(record["organic_results"])
8
8
  """
9
9
 
10
- __version__ = "0.1.1"
10
+ __version__ = "0.1.2"
11
11
 
12
12
  from .classify import Verdict, classify # noqa: E402
13
13
  from .parse import parse_serp # noqa: E402
@@ -229,6 +229,61 @@ class Headers:
229
229
  # -- the session ------------------------------------------------------------------
230
230
 
231
231
 
232
+ class LinkClient:
233
+ """Asks Google's host for a path on the exit a page came over HTTP from, with
234
+ that page's cookies and Chromium's headers as for a click from the results
235
+ page. For the link resolver's thread: it has an HTTP client of its own, so it
236
+ never shares one with the session's searches."""
237
+
238
+ def __init__(self, proxy_url: str, request: dict, cookie: str, origin: str, http=None) -> None:
239
+ self._proxy_url = proxy_url
240
+ self._request = request
241
+ self._cookie = cookie
242
+ self._origin = origin
243
+ self._http = http
244
+
245
+ def _headers(self) -> list[tuple[str, str]]:
246
+ out, referer = [], ("referer", self._origin + "/")
247
+ for name, value in replay_headers(self._request, self._cookie):
248
+ if name == "referer":
249
+ continue
250
+ out.append((name, "same-origin" if name == "sec-fetch-site" else value))
251
+ if name == "accept-language":
252
+ out.append(referer)
253
+ return out if referer in out else out + [referer]
254
+
255
+ def get(self, path: str, timeout: float = TIMEOUT) -> tuple[int, str, str] | None:
256
+ """Status, Location and body of `path`, redirects not followed, within
257
+ `timeout` seconds (at most `TIMEOUT`); None on an error."""
258
+ if self._http is None:
259
+ from curl_cffi import requests as cr
260
+
261
+ self._http = cr.Session(
262
+ impersonate=impersonate_for(self._request),
263
+ default_headers=False,
264
+ proxies={"http": self._proxy_url, "https": self._proxy_url},
265
+ timeout=TIMEOUT,
266
+ )
267
+ try:
268
+ response = self._http.get(
269
+ self._origin + path,
270
+ headers=self._headers(),
271
+ allow_redirects=False,
272
+ timeout=min(timeout, TIMEOUT),
273
+ )
274
+ except Exception:
275
+ return None
276
+ return response.status_code, response.headers.get("location") or "", response.text
277
+
278
+ def close(self) -> None:
279
+ if self._http is not None:
280
+ try:
281
+ self._http.close()
282
+ except Exception:
283
+ pass
284
+ self._http = None
285
+
286
+
232
287
  class HybridSession:
233
288
  """A browser session whose results pages come over HTTP while Google
234
289
  serves them there, and from the browser otherwise.
@@ -392,6 +447,16 @@ class HybridSession:
392
447
  )
393
448
  return self._browser(self.inner.next_page, None)
394
449
 
450
+ def link_client(self) -> LinkClient | None:
451
+ """For the page this session just fetched, over HTTP or in the browser:
452
+ what its links are asked with, on this exit and with the cookies as
453
+ they are now. None until Chromium's request headers have been read."""
454
+ if self._headers.request is None or not self._proxy_url or not self._cookie:
455
+ return None
456
+ home = urlsplit(search_page())
457
+ origin = f"{home.scheme}://{home.netloc}"
458
+ return LinkClient(self._proxy_url, self._headers.request, self._cookie, origin)
459
+
395
460
  def _browser(self, call, query: str | None, page: int = 1) -> Fetched | None:
396
461
  if self._cookie:
397
462
  self.inner.set_google_cookies(self._cookie, tuple(sorted(self._deleted)))
@@ -7,11 +7,19 @@ works from any client, so a link costs one small request.
7
7
  The resolver uses its own sticky proxy session, never the browser's, so link
8
8
  resolution does not touch the warmed browser session, and its traffic goes
9
9
  through a relay so it is counted like everything else.
10
+
11
+ A page that came over HTTP is resolved on its own exit instead: each result's
12
+ anchor carries a ping URL, which Google answers there with a small page naming
13
+ the destination. Its /goto answers with a destination only for the few results
14
+ it prefetches, and asked from a fresh exit it is refused.
10
15
  """
11
16
 
12
17
  from __future__ import annotations
13
18
 
19
+ import html
20
+ import re
14
21
  import threading
22
+ import time
15
23
  import urllib.error
16
24
  import urllib.request
17
25
  from collections.abc import Callable
@@ -19,6 +27,8 @@ from concurrent.futures import ThreadPoolExecutor
19
27
  from typing import Any
20
28
  from urllib.parse import urlsplit
21
29
 
30
+ from lxml import html as lxml_html
31
+
22
32
  from .relay import Relay
23
33
 
24
34
  UA = (
@@ -28,6 +38,36 @@ UA = (
28
38
  TIMEOUT_S = 30
29
39
  #: /goto links resolved at once for one page.
30
40
  PARALLEL = 4
41
+ #: Seconds one page's ping lookups may take; the rest go to the /goto resolver.
42
+ PING_BUDGET_S = 30.0
43
+ #: Google's answer to a ping URL names the destination in a refresh tag and in
44
+ #: the script that navigates to it.
45
+ _REFRESH = re.compile(r'<meta[^>]*content="0;url=([^"]+)"')
46
+ _SCRIPT = re.compile(r"redirectUrl='([^']+)'")
47
+
48
+
49
+ def ping_paths(page: str) -> dict[str, str]:
50
+ """Each result anchor's /goto href, mapped to the same anchor's ping URL."""
51
+ paths: dict[str, str] = {}
52
+ for anchor in lxml_html.fromstring(page).iter("a"):
53
+ href, ping = anchor.get("href") or "", anchor.get("ping") or ""
54
+ if href.startswith("/goto?") and ping.startswith("/url?"):
55
+ paths.setdefault(href, ping)
56
+ return paths
57
+
58
+
59
+ def ping_destination(body: str) -> str | None:
60
+ """The destination named by Google's answer to a ping URL."""
61
+ if match := _REFRESH.search(body):
62
+ return html.unescape(match.group(1))
63
+ if match := _SCRIPT.search(body):
64
+ return re.sub(r"\\x([0-9a-fA-F]{2})", lambda m: chr(int(m.group(1), 16)), match.group(1))
65
+ return None
66
+
67
+
68
+ def _refused(location: str) -> bool:
69
+ host = urlsplit(location).netloc.lower()
70
+ return "/sorry" in location or host.startswith(("sorry.", "consent."))
31
71
 
32
72
 
33
73
  class _AlwaysProxy(urllib.request.ProxyHandler):
@@ -114,8 +154,7 @@ class LinkResolver:
114
154
  with self._lock:
115
155
  self.failed += 1
116
156
  return None
117
- host = urlsplit(location or "").netloc.lower()
118
- if not location or "/sorry" in location or host.startswith(("sorry.", "consent.")):
157
+ if not location or _refused(location):
119
158
  with self._lock:
120
159
  self.failed += 1
121
160
  self.enabled = False
@@ -142,6 +181,52 @@ class LinkResolver:
142
181
  for result, link in zip(todo, links, strict=True):
143
182
  result["link"] = link
144
183
 
184
+ def fill_from_pings(
185
+ self,
186
+ results: list[dict[str, Any]],
187
+ page: str,
188
+ get: Callable[[str, float], tuple[int, str, str] | None],
189
+ ) -> None:
190
+ """Resolve a page's /goto links on the exit the page came from.
191
+
192
+ `get(path, timeout)` asks Google's host for `path` there within
193
+ `timeout` seconds and returns the status, the Location and the body, or
194
+ None on an error. Each result is asked
195
+ through its anchor's ping URL. A refusal or an error ends asking for
196
+ this page, as does `PING_BUDGET_S`; the resolver itself stays on, since
197
+ another exit is another answer. A result left without a link is counted
198
+ by `fill`, which tries it next, or here when `fill` will not.
199
+ """
200
+ pings = ping_paths(page)
201
+ deadline = time.monotonic() + PING_BUDGET_S
202
+ for result in results:
203
+ redirect = result.get("redirect_link") or ""
204
+ if result.get("link") is not None or "/goto?" not in redirect:
205
+ continue
206
+ path = pings.get("/goto?" + redirect.split("/goto?", 1)[1])
207
+ if path is None:
208
+ continue
209
+ left = deadline - time.monotonic()
210
+ if left <= 0:
211
+ return
212
+ answer = get(path, left)
213
+ if answer is None:
214
+ return
215
+ status, location, body = answer
216
+ if _refused(location):
217
+ return
218
+ link = None
219
+ if 300 <= status < 400:
220
+ link = location or None
221
+ elif status == 200:
222
+ link = ping_destination(body)
223
+ with self._lock:
224
+ if link:
225
+ self.resolved += 1
226
+ result["link"] = link
227
+ elif not self.enabled:
228
+ self.failed += 1
229
+
145
230
  def close(self) -> None:
146
231
  if self._relay is not None:
147
232
  self._relay.stop()
@@ -582,9 +582,19 @@ class Stats:
582
582
  return out
583
583
 
584
584
 
585
- def _fill_links(resolver, record: dict[str, Any]) -> None:
585
+ def _fill_links(resolver, record: dict[str, Any], page: str = "", client=None) -> None:
586
+ """A record's links: on the exit its page came from, through each result's
587
+ ping URL, then from the resolver's own exit for whatever is left."""
586
588
  mark = time.monotonic()
587
- resolver.fill(record.get("organic_results") or [])
589
+ results = record.get("organic_results") or []
590
+ if client is not None:
591
+ try:
592
+ resolver.fill_from_pings(results, page, client.get)
593
+ except Exception:
594
+ pass # whatever is left goes to the /goto resolver below
595
+ finally:
596
+ client.close()
597
+ resolver.fill(results)
588
598
  record["search_metadata"].setdefault("timings", {})["links"] = round(time.monotonic() - mark, 2)
589
599
 
590
600
 
@@ -634,6 +644,9 @@ class Pinned:
634
644
  def needs_restart(self) -> bool:
635
645
  return self._call(getattr(self.session, "needs_restart", lambda: False))
636
646
 
647
+ def link_client(self) -> Any:
648
+ return self._call(getattr(self.session, "link_client", lambda: None))
649
+
637
650
  def blank(self) -> None:
638
651
  self._call(self.session.blank)
639
652
 
@@ -1044,7 +1057,11 @@ class Scraper:
1044
1057
  if resolver is not None:
1045
1058
  if self._link_pool is None:
1046
1059
  self._link_pool = ThreadPoolExecutor(1, thread_name_prefix="gbs-links")
1047
- self._link_jobs[id(record)] = self._link_pool.submit(_fill_links, resolver, record)
1060
+ make = getattr(identity.session, "link_client", None)
1061
+ client = make() if make else None
1062
+ self._link_jobs[id(record)] = self._link_pool.submit(
1063
+ _fill_links, resolver, record, fetched.html, client
1064
+ )
1048
1065
  return record
1049
1066
 
1050
1067
  def _links_ready(self, record: dict[str, Any]) -> bool:
@@ -1402,6 +1419,12 @@ class Scraper:
1402
1419
  self._close_identity(identity, reason)
1403
1420
 
1404
1421
  def _close_identity(self, identity: Identity, reason: str) -> None:
1422
+ # Links of its last pages are asked on its exit, which closes with it.
1423
+ for job in list(self._link_jobs.values()):
1424
+ try:
1425
+ job.result()
1426
+ except Exception:
1427
+ pass
1405
1428
  try:
1406
1429
  identity.session.close()
1407
1430
  finally:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: google-browser-scraper
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Google Search results from a real browser through your own sticky proxy, with captchas and blocks reported explicitly.
5
5
  Author: NodeMaven
6
6
  License: MIT
@@ -368,9 +368,10 @@ copies carrying the cache are refused on their first search, the rest of the
368
368
  run copies cookies only (`--no-clone-cache` does that from the start).
369
369
 
370
370
  **Result links.** Google wraps result links in encrypted `/goto` redirects.
371
- Each one is resolved with a small request through a separate short-lived proxy
372
- session, a few at a time, in the background while the browser goes on to the
373
- next query. Records still come out in the order each browser searched them.
371
+ Each one is resolved with a small request on the proxy IP the page came from,
372
+ with that page's cookies, in the background while the next query runs; a link
373
+ left over is tried through a separate short-lived proxy session. Records still
374
+ come out in the order each browser searched them.
374
375
 
375
376
  **Traffic.** Everything goes through a small local relay that counts bytes per
376
377
  host and blocks a large model download Chrome otherwise makes on every fresh
@@ -7,7 +7,7 @@ import pages
7
7
 
8
8
  from google_browser_scraper import hybrid, quality
9
9
  from google_browser_scraper.browser import Fetched
10
- from google_browser_scraper.hybrid import Headers, HybridSession
10
+ from google_browser_scraper.hybrid import Headers, HybridSession, LinkClient
11
11
 
12
12
  SEARCH = "https://www.google.com/search?q=x"
13
13
  SERVED = Fetched(SEARCH, 200, pages.results_page())
@@ -43,8 +43,9 @@ class Client:
43
43
  def __init__(self, script):
44
44
  self.script, self.sent = list(script), []
45
45
 
46
- def get(self, url, headers):
46
+ def get(self, url, headers, **options):
47
47
  self.sent.append((url, headers))
48
+ self.options = options
48
49
  item = self.script.pop(0)
49
50
  if isinstance(item, Exception):
50
51
  raise item
@@ -408,3 +409,59 @@ def test_a_page_with_only_places_is_served_over_http():
408
409
  s, _ = session(client)
409
410
  fetched = s.search("pizza near me", direct=True)
410
411
  assert fetched.timings.get("http") is not None and s.inner.searched == []
412
+
413
+
414
+ def test_links_of_an_http_page_are_asked_on_its_exit_with_its_cookies():
415
+ client = Client([Response(SERVED.html, set_cookie=["NID=2"])])
416
+ s, _ = session(client)
417
+ s.search("best running shoes", direct=True)
418
+ links = s.link_client()
419
+ assert links._proxy_url == "http://127.0.0.1:1" # the page's own proxy IP
420
+ asked = Client([Response("<html></html>", status=302)])
421
+ links._http = asked
422
+ links.get("/url?sa=t&url=AAA")
423
+ url, headers = asked.sent[0]
424
+ assert url == "https://www.google.com/url?sa=t&url=AAA"
425
+ assert dict(headers)["cookie"] == "SID=browser; NID=2"
426
+ assert dict(headers)["referer"] == "https://www.google.com/"
427
+ assert asked.options == {"allow_redirects": False, "timeout": hybrid.TIMEOUT}
428
+
429
+
430
+ def test_a_page_the_browser_rendered_is_asked_with_the_browsers_cookies():
431
+ s, _ = session(Client([]), opened=False)
432
+ s.search("a b", direct=True) # an exit's first query goes through the browser
433
+ assert s.link_client()._cookie == "SID=browser"
434
+
435
+
436
+ def test_no_link_client_before_chromiums_headers_are_read():
437
+ s, _ = session(Client([]), headers=Headers())
438
+ s.search("q", direct=True)
439
+ assert s.link_client() is None
440
+
441
+
442
+ def test_link_headers_carry_one_referer_even_if_the_template_had_one():
443
+ request = {"headers": [("accept-language", "en"), ("referer", "https://x.example/")]}
444
+ out = LinkClient("http://127.0.0.1:1", request, "", "https://www.google.com")._headers()
445
+ assert [v for n, v in out if n == "referer"] == ["https://www.google.com/"]
446
+
447
+
448
+ def test_link_headers_say_same_origin_after_the_language():
449
+ request = {
450
+ "headers": [("sec-fetch-site", "none"), ("accept-language", "en"), ("cookie", "X=1")]
451
+ }
452
+ out = LinkClient("http://127.0.0.1:1", request, "Y=2", "https://www.google.com")._headers()
453
+ assert out == [
454
+ ("sec-fetch-site", "same-origin"),
455
+ ("accept-language", "en"),
456
+ ("referer", "https://www.google.com/"),
457
+ ("cookie", "Y=2"),
458
+ ]
459
+
460
+
461
+ def test_a_link_request_never_waits_longer_than_asked():
462
+ s, _ = session(Client([Response(SERVED.html)]))
463
+ s.search("best running shoes", direct=True)
464
+ links = s.link_client()
465
+ links._http = asked = Client([Response("<html></html>", status=302)])
466
+ links.get("/url?sa=t&url=AAA", 3.5)
467
+ assert asked.options["timeout"] == 3.5
@@ -0,0 +1,273 @@
1
+ """The /goto resolver against a local server that answers like Google."""
2
+
3
+ import threading
4
+ import time
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+
7
+ import pytest
8
+
9
+ from google_browser_scraper.links import PING_BUDGET_S, LinkResolver, ping_destination, ping_paths
10
+ from google_browser_scraper.scraper import _fill_links
11
+
12
+
13
+ class Handler(BaseHTTPRequestHandler):
14
+ def do_GET(self): # noqa: N802 - the stdlib's name
15
+ if "sorry" in self.path:
16
+ target = "https://www.google.com/sorry/index?continue=x"
17
+ elif "none" in self.path:
18
+ target = None
19
+ else:
20
+ target = "https://www.runnersworld.com/gear/a25750345/running-shoes-flat-feet/"
21
+ self.send_response(302 if target else 200)
22
+ if target:
23
+ self.send_header("Location", target)
24
+ self.send_header("Content-Length", "0")
25
+ self.end_headers()
26
+
27
+ def log_message(self, *args):
28
+ pass
29
+
30
+
31
+ @pytest.fixture
32
+ def goto_server():
33
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
34
+ threading.Thread(target=server.serve_forever, daemon=True).start()
35
+ yield f"http://127.0.0.1:{server.server_port}"
36
+ server.shutdown()
37
+
38
+
39
+ def test_a_302_location_is_the_destination_and_is_counted(goto_server):
40
+ resolver = LinkResolver(None) # direct, through the counting relay
41
+ try:
42
+ link = resolver.resolve(f"{goto_server}/goto?url=CAESabc")
43
+ finally:
44
+ resolver.close()
45
+ assert link == "https://www.runnersworld.com/gear/a25750345/running-shoes-flat-feet/"
46
+ assert resolver.resolved == 1 and resolver.bytes > 0
47
+
48
+
49
+ def test_a_sorry_redirect_disables_the_resolver(goto_server):
50
+ resolver = LinkResolver(None)
51
+ try:
52
+ assert resolver.resolve(f"{goto_server}/goto?url=sorry") is None
53
+ assert not resolver.enabled
54
+ assert resolver.resolve(f"{goto_server}/goto?url=CAESabc") is None # not even asked
55
+ finally:
56
+ resolver.close()
57
+ assert resolver.failed == 1 and resolver.resolved == 0
58
+
59
+
60
+ def test_no_location_is_a_failure(goto_server):
61
+ resolver = LinkResolver(None)
62
+ try:
63
+ assert resolver.resolve(f"{goto_server}/goto?url=none") is None
64
+ finally:
65
+ resolver.close()
66
+
67
+
68
+ def test_fill_only_touches_unresolved_goto_results(goto_server):
69
+ resolver = LinkResolver(None)
70
+ results = [
71
+ {"link": "https://kept.example/", "redirect_link": f"{goto_server}/goto?url=a"},
72
+ {"link": None, "redirect_link": f"{goto_server}/goto?url=b"},
73
+ {"link": None},
74
+ ]
75
+ try:
76
+ resolver.fill(results)
77
+ finally:
78
+ resolver.close()
79
+ assert [r["link"] for r in results] == [
80
+ "https://kept.example/",
81
+ "https://www.runnersworld.com/gear/a25750345/running-shoes-flat-feet/",
82
+ None,
83
+ ]
84
+
85
+
86
+ def test_an_upstream_the_relay_cannot_speak_disables_resolving():
87
+ resolver = LinkResolver({"server": "socks5://127.0.0.1:1080"})
88
+ assert not resolver.enabled
89
+ assert resolver.resolve("https://www.google.com/goto?url=x") is None
90
+ resolver.close()
91
+
92
+
93
+ def test_fill_resolves_several_links_at_once_and_keeps_their_order():
94
+ resolver = LinkResolver(None, relay_factory=None)
95
+ running, peak = [0], [0]
96
+ lock = threading.Lock()
97
+
98
+ def slow(url):
99
+ with lock:
100
+ running[0] += 1
101
+ peak[0] = max(peak[0], running[0])
102
+ time.sleep(0.05)
103
+ with lock:
104
+ running[0] -= 1
105
+ return url.replace("https://www.google.com/goto?url=", "")
106
+
107
+ resolver.resolve = slow
108
+ results = [
109
+ {"redirect_link": f"https://www.google.com/goto?url=https://e{i}.com/"} for i in range(8)
110
+ ]
111
+ resolver.fill(results)
112
+ assert [r["link"] for r in results] == [f"https://e{i}.com/" for i in range(8)]
113
+ assert peak[0] > 1
114
+
115
+
116
+ def ping_answer(url):
117
+ # Google's answer to a ping URL, as served: a script and a refresh tag.
118
+ script_url = url.replace("&", "\x26")
119
+ return (
120
+ '<html lang="en"><head><meta content="origin" name="referrer"><script nonce="n">'
121
+ f"(function(){{var redirectUrl='{script_url}';"
122
+ "google.navigateTo(parent,window,redirectUrl);})();"
123
+ f'</script><noscript><meta content="0;url={url.replace("&", "&amp;")}" '
124
+ 'http-equiv="refresh"></noscript></head></html>'
125
+ )
126
+
127
+
128
+ PAGE = (
129
+ "<html><body>"
130
+ '<a href="/goto?url=AAA" ping="/url?sa=t&amp;source=web&amp;url=AAA&amp;ved=1">one</a>'
131
+ '<a href="/goto?url=BBB" ping="/url?sa=t&amp;source=web&amp;url=BBB&amp;ved=2">two</a>'
132
+ '<a href="/goto?url=CCC">no ping</a>'
133
+ "</body></html>"
134
+ )
135
+
136
+
137
+ def test_a_ping_answer_names_the_destination():
138
+ assert ping_destination(ping_answer("https://e.com/a?b=1&c=2")) == "https://e.com/a?b=1&c=2"
139
+ script_only = r"<script>var redirectUrl='https://e.com/x\x3dy';</script>"
140
+ assert ping_destination(script_only) == "https://e.com/x=y"
141
+ assert ping_destination("<html>Loading...</html>") is None
142
+
143
+
144
+ def test_ping_paths_map_each_goto_href_to_its_anchors_ping():
145
+ assert ping_paths(PAGE) == {
146
+ "/goto?url=AAA": "/url?sa=t&source=web&url=AAA&ved=1",
147
+ "/goto?url=BBB": "/url?sa=t&source=web&url=BBB&ved=2",
148
+ }
149
+
150
+
151
+ def test_pings_resolve_every_result_of_a_page_on_its_exit():
152
+ asked = []
153
+
154
+ def get(path, timeout):
155
+ asked.append(path)
156
+ token = path.split("url=")[1].split("&")[0]
157
+ return 200, "", ping_answer(f"https://{token.lower()}.example/page")
158
+
159
+ resolver = LinkResolver(None, relay_factory=None)
160
+ results = [
161
+ {"link": None, "redirect_link": "https://www.google.com/goto?url=AAA"},
162
+ {"link": "https://kept.example/", "redirect_link": "https://www.google.com/goto?url=BBB"},
163
+ {"link": None, "redirect_link": "https://www.google.com/goto?url=BBB"},
164
+ {"link": None, "redirect_link": "https://www.google.com/goto?url=CCC"},
165
+ ]
166
+ resolver.fill_from_pings(results, PAGE, get)
167
+ assert [r["link"] for r in results] == [
168
+ "https://aaa.example/page",
169
+ "https://kept.example/",
170
+ "https://bbb.example/page",
171
+ None, # no ping on its anchor: left for the /goto resolver
172
+ ]
173
+ assert len(asked) == 2 and resolver.resolved == 2 and resolver.enabled
174
+
175
+
176
+ def test_a_refused_ping_ends_asking_for_that_page_only():
177
+ asked = []
178
+
179
+ def get(path, timeout):
180
+ asked.append(path)
181
+ return 302, "https://www.google.com/sorry/index?continue=x", ""
182
+
183
+ resolver = LinkResolver(None, relay_factory=None)
184
+ results = [
185
+ {"link": None, "redirect_link": f"https://www.google.com/goto?url={t}"}
186
+ for t in ("AAA", "BBB")
187
+ ]
188
+ resolver.fill_from_pings(results, PAGE, get)
189
+ # Left for the /goto resolver, which tries them next and counts them.
190
+ assert len(asked) == 1 and resolver.failed == 0 and resolver.enabled
191
+ assert [r["link"] for r in results] == [None, None]
192
+
193
+
194
+ def test_an_error_on_a_ping_stops_asking_for_that_page():
195
+ asked = []
196
+
197
+ def get(path, timeout):
198
+ asked.append(path)
199
+ return None
200
+
201
+ resolver = LinkResolver(None, relay_factory=None)
202
+ results = [
203
+ {"link": None, "redirect_link": f"https://www.google.com/goto?url={t}"}
204
+ for t in ("AAA", "BBB")
205
+ ]
206
+ resolver.fill_from_pings(results, PAGE, get)
207
+ assert len(asked) == 1
208
+
209
+
210
+ def test_a_miss_is_counted_once_when_no_goto_resolver_follows():
211
+ resolver = LinkResolver(None, relay_factory=None)
212
+ resolver.enabled = False
213
+ results = [{"link": None, "redirect_link": "https://www.google.com/goto?url=AAA"}]
214
+ resolver.fill_from_pings(
215
+ results, PAGE, lambda path, timeout: (200, "", "<html>Loading...</html>")
216
+ )
217
+ resolver.fill(results)
218
+ assert resolver.failed == 1 and resolver.resolved == 0
219
+
220
+
221
+ def test_a_ping_lookup_that_raises_still_leaves_the_rest_to_goto():
222
+ class Client:
223
+ def get(self, path, timeout):
224
+ raise RuntimeError("broken")
225
+
226
+ def close(self):
227
+ pass
228
+
229
+ resolver = LinkResolver(None, relay_factory=None)
230
+ filled = []
231
+ resolver.fill = lambda results: filled.append(len(results))
232
+ record = {
233
+ "organic_results": [{"link": None, "redirect_link": "https://www.google.com/goto?url=AAA"}],
234
+ "search_metadata": {},
235
+ }
236
+ _fill_links(resolver, record, PAGE, Client())
237
+ assert filled == [1]
238
+
239
+
240
+ def test_a_record_from_http_is_resolved_on_its_exit_and_the_client_closed():
241
+ class Client:
242
+ closed = False
243
+
244
+ def get(self, path, timeout):
245
+ return 200, "", ping_answer("https://aaa.example/")
246
+
247
+ def close(self):
248
+ Client.closed = True
249
+
250
+ resolver = LinkResolver(None, relay_factory=None)
251
+ resolver.enabled = False # the /goto resolver has nothing to add here
252
+ record = {
253
+ "organic_results": [{"link": None, "redirect_link": "https://www.google.com/goto?url=AAA"}],
254
+ "search_metadata": {},
255
+ }
256
+ _fill_links(resolver, record, PAGE, Client())
257
+ assert record["organic_results"][0]["link"] == "https://aaa.example/" and Client.closed
258
+
259
+
260
+ def test_each_ping_gets_what_is_left_of_the_page_budget():
261
+ timeouts = []
262
+
263
+ def get(path, timeout):
264
+ timeouts.append(timeout)
265
+ return 200, "", ping_answer("https://aaa.example/")
266
+
267
+ resolver = LinkResolver(None, relay_factory=None)
268
+ results = [
269
+ {"link": None, "redirect_link": f"https://www.google.com/goto?url={t}"}
270
+ for t in ("AAA", "BBB")
271
+ ]
272
+ resolver.fill_from_pings(results, PAGE, get)
273
+ assert len(timeouts) == 2 and 0 < timeouts[1] <= timeouts[0] <= PING_BUDGET_S
@@ -11,6 +11,7 @@ from google_browser_scraper.proxy import ProxyTemplate
11
11
  from google_browser_scraper.scraper import (
12
12
  PREWARM_QUERIES,
13
13
  ExitsRefused,
14
+ Pinned,
14
15
  ProxyRefused,
15
16
  Scraper,
16
17
  Settings,
@@ -1249,3 +1250,16 @@ def test_a_poisoned_page_does_not_reset_the_breaker():
1249
1250
  # Two pages before the streak and the third on the new exit reset it; the
1250
1251
  # poisoned third page on the first exit does not.
1251
1252
  assert len(resets) == 3
1253
+
1254
+
1255
+ def test_a_spare_passes_its_link_client_through():
1256
+ class Hybrid:
1257
+ def link_client(self):
1258
+ return "client"
1259
+
1260
+ with_client, without = Pinned(lambda: Hybrid()), Pinned(lambda: object())
1261
+ try:
1262
+ assert with_client.link_client() == "client" and without.link_client() is None
1263
+ finally:
1264
+ with_client._thread.shutdown(wait=False)
1265
+ without._thread.shutdown(wait=False)
@@ -1,112 +0,0 @@
1
- """The /goto resolver against a local server that answers like Google."""
2
-
3
- import threading
4
- import time
5
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
-
7
- import pytest
8
-
9
- from google_browser_scraper.links import LinkResolver
10
-
11
-
12
- class Handler(BaseHTTPRequestHandler):
13
- def do_GET(self): # noqa: N802 - the stdlib's name
14
- if "sorry" in self.path:
15
- target = "https://www.google.com/sorry/index?continue=x"
16
- elif "none" in self.path:
17
- target = None
18
- else:
19
- target = "https://www.runnersworld.com/gear/a25750345/running-shoes-flat-feet/"
20
- self.send_response(302 if target else 200)
21
- if target:
22
- self.send_header("Location", target)
23
- self.send_header("Content-Length", "0")
24
- self.end_headers()
25
-
26
- def log_message(self, *args):
27
- pass
28
-
29
-
30
- @pytest.fixture
31
- def goto_server():
32
- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
33
- threading.Thread(target=server.serve_forever, daemon=True).start()
34
- yield f"http://127.0.0.1:{server.server_port}"
35
- server.shutdown()
36
-
37
-
38
- def test_a_302_location_is_the_destination_and_is_counted(goto_server):
39
- resolver = LinkResolver(None) # direct, through the counting relay
40
- try:
41
- link = resolver.resolve(f"{goto_server}/goto?url=CAESabc")
42
- finally:
43
- resolver.close()
44
- assert link == "https://www.runnersworld.com/gear/a25750345/running-shoes-flat-feet/"
45
- assert resolver.resolved == 1 and resolver.bytes > 0
46
-
47
-
48
- def test_a_sorry_redirect_disables_the_resolver(goto_server):
49
- resolver = LinkResolver(None)
50
- try:
51
- assert resolver.resolve(f"{goto_server}/goto?url=sorry") is None
52
- assert not resolver.enabled
53
- assert resolver.resolve(f"{goto_server}/goto?url=CAESabc") is None # not even asked
54
- finally:
55
- resolver.close()
56
- assert resolver.failed == 1 and resolver.resolved == 0
57
-
58
-
59
- def test_no_location_is_a_failure(goto_server):
60
- resolver = LinkResolver(None)
61
- try:
62
- assert resolver.resolve(f"{goto_server}/goto?url=none") is None
63
- finally:
64
- resolver.close()
65
-
66
-
67
- def test_fill_only_touches_unresolved_goto_results(goto_server):
68
- resolver = LinkResolver(None)
69
- results = [
70
- {"link": "https://kept.example/", "redirect_link": f"{goto_server}/goto?url=a"},
71
- {"link": None, "redirect_link": f"{goto_server}/goto?url=b"},
72
- {"link": None},
73
- ]
74
- try:
75
- resolver.fill(results)
76
- finally:
77
- resolver.close()
78
- assert [r["link"] for r in results] == [
79
- "https://kept.example/",
80
- "https://www.runnersworld.com/gear/a25750345/running-shoes-flat-feet/",
81
- None,
82
- ]
83
-
84
-
85
- def test_an_upstream_the_relay_cannot_speak_disables_resolving():
86
- resolver = LinkResolver({"server": "socks5://127.0.0.1:1080"})
87
- assert not resolver.enabled
88
- assert resolver.resolve("https://www.google.com/goto?url=x") is None
89
- resolver.close()
90
-
91
-
92
- def test_fill_resolves_several_links_at_once_and_keeps_their_order():
93
- resolver = LinkResolver(None, relay_factory=None)
94
- running, peak = [0], [0]
95
- lock = threading.Lock()
96
-
97
- def slow(url):
98
- with lock:
99
- running[0] += 1
100
- peak[0] = max(peak[0], running[0])
101
- time.sleep(0.05)
102
- with lock:
103
- running[0] -= 1
104
- return url.replace("https://www.google.com/goto?url=", "")
105
-
106
- resolver.resolve = slow
107
- results = [
108
- {"redirect_link": f"https://www.google.com/goto?url=https://e{i}.com/"} for i in range(8)
109
- ]
110
- resolver.fill(results)
111
- assert [r["link"] for r in results] == [f"https://e{i}.com/" for i in range(8)]
112
- assert peak[0] > 1