stealth-requests 2.0.6__tar.gz → 2.2.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 (20) hide show
  1. {stealth_requests-2.0.6/stealth_requests.egg-info → stealth_requests-2.2.0}/PKG-INFO +10 -9
  2. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/README.md +3 -3
  3. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/pyproject.toml +11 -12
  4. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/stealth_requests/response.py +1 -1
  5. stealth_requests-2.2.0/stealth_requests/session.py +173 -0
  6. {stealth_requests-2.0.6 → stealth_requests-2.2.0/stealth_requests.egg-info}/PKG-INFO +10 -9
  7. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/stealth_requests.egg-info/SOURCES.txt +2 -1
  8. stealth_requests-2.2.0/stealth_requests.egg-info/requires.txt +7 -0
  9. stealth_requests-2.2.0/tests/test_identity.py +114 -0
  10. stealth_requests-2.2.0/tests/test_referer.py +40 -0
  11. stealth_requests-2.0.6/stealth_requests/session.py +0 -114
  12. stealth_requests-2.0.6/stealth_requests/user_agents.json +0 -61
  13. stealth_requests-2.0.6/stealth_requests.egg-info/requires.txt +0 -6
  14. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/LICENSE +0 -0
  15. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/setup.cfg +0 -0
  16. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/stealth_requests/__init__.py +0 -0
  17. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/stealth_requests.egg-info/dependency_links.txt +0 -0
  18. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/stealth_requests.egg-info/top_level.txt +0 -0
  19. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/tests/test_requests.py +0 -0
  20. {stealth_requests-2.0.6 → stealth_requests-2.2.0}/tests/test_response.py +0 -0
@@ -1,19 +1,20 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stealth-requests
3
- Version: 2.0.6
3
+ Version: 2.2.0
4
4
  Summary: Undetected web-scraping & seamless HTML parsing in Python!
5
5
  Author-email: Jacob Padilla <stealth-requests@jacobpadilla.com>
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://github.com/jpjacobpadilla/Stealth-Requests
8
8
  Keywords: HTTP,requests,scraping,browser
9
- Requires-Python: >=3.10
9
+ Requires-Python: >=3.11.5
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
- Requires-Dist: curl_cffi>=0.14.0
12
+ Requires-Dist: curl_cffi>=0.17.0
13
13
  Provides-Extra: parsers
14
- Requires-Dist: lxml; extra == "parsers"
15
- Requires-Dist: html2text; extra == "parsers"
16
- Requires-Dist: beautifulsoup4; extra == "parsers"
14
+ Requires-Dist: lxml>=6.1.0; extra == "parsers"
15
+ Requires-Dist: html2text>=2025.4.15; extra == "parsers"
16
+ Requires-Dist: beautifulsoup4>=4.13.0; extra == "parsers"
17
+ Requires-Dist: soupsieve>=4.0.0; extra == "parsers"
17
18
  Dynamic: license-file
18
19
 
19
20
  <p align="center">
@@ -22,14 +23,14 @@ Dynamic: license-file
22
23
 
23
24
  <h1 align="center">The Easiest Way to Scrape the Web</h1>
24
25
 
25
- <p align="center"><a href="https://github.com/jpjacobpadilla/stealth-requests/blob/main/LICENSE"><img src="https://img.shields.io/github/license/jpjacobpadilla/stealth-requests.svg?color=green"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.10%2B-green" alt="Python 3.10+"></a> <a href="https://pypi.org/project/stealth-requests/"><img alt="PyPI" src="https://img.shields.io/pypi/v/stealth-requests.svg?color=green"></a> <a href="https://pepy.tech/project/stealth-requests"><img alt="PyPI installs" src="https://img.shields.io/pepy/dt/stealth-requests?label=pypi%20installs&color=green"></a></p>
26
+ <p align="center"><a href="https://github.com/jpjacobpadilla/stealth-requests/blob/main/LICENSE"><img src="https://img.shields.io/github/license/jpjacobpadilla/stealth-requests.svg?color=97ca00"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.11%2B-97ca00" alt="Python 3.11+"></a> <a href="https://pypi.org/project/stealth-requests/"><img alt="PyPI" src="https://img.shields.io/pypi/v/stealth-requests.svg?color=97ca00"></a> <a href="https://pepy.tech/project/stealth-requests"><img alt="PyPI installs" src="https://static.pepy.tech/personalized-badge/stealth-requests?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=pypi%20installs"></a></p>
26
27
 
27
28
 
28
29
  ### Features
29
30
  - **Realistic HTTP Requests:**
30
31
  - Mimics Chrome browser for undetected scraping using [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/)
31
- - Automatically rotates User Agents between requests
32
- - Tracks and updates the `Referer` header to simulate realistic request chains
32
+ - Sends a consistent macOS Chrome User-Agent and client hints that match the impersonated browser
33
+ - Tracks and updates the `Referer` header to simulate realistic request chains (following Chrome's default referrer policy, so full URLs never leak to other sites)
33
34
  - Built-in retry logic for failed requests (e.g. 429, 503, 522)
34
35
  - **Faster and Easier Parsing:**
35
36
  - Extract emails, phone numbers, images, and links from responses
@@ -4,14 +4,14 @@
4
4
 
5
5
  <h1 align="center">The Easiest Way to Scrape the Web</h1>
6
6
 
7
- <p align="center"><a href="https://github.com/jpjacobpadilla/stealth-requests/blob/main/LICENSE"><img src="https://img.shields.io/github/license/jpjacobpadilla/stealth-requests.svg?color=green"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.10%2B-green" alt="Python 3.10+"></a> <a href="https://pypi.org/project/stealth-requests/"><img alt="PyPI" src="https://img.shields.io/pypi/v/stealth-requests.svg?color=green"></a> <a href="https://pepy.tech/project/stealth-requests"><img alt="PyPI installs" src="https://img.shields.io/pepy/dt/stealth-requests?label=pypi%20installs&color=green"></a></p>
7
+ <p align="center"><a href="https://github.com/jpjacobpadilla/stealth-requests/blob/main/LICENSE"><img src="https://img.shields.io/github/license/jpjacobpadilla/stealth-requests.svg?color=97ca00"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.11%2B-97ca00" alt="Python 3.11+"></a> <a href="https://pypi.org/project/stealth-requests/"><img alt="PyPI" src="https://img.shields.io/pypi/v/stealth-requests.svg?color=97ca00"></a> <a href="https://pepy.tech/project/stealth-requests"><img alt="PyPI installs" src="https://static.pepy.tech/personalized-badge/stealth-requests?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=pypi%20installs"></a></p>
8
8
 
9
9
 
10
10
  ### Features
11
11
  - **Realistic HTTP Requests:**
12
12
  - Mimics Chrome browser for undetected scraping using [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/)
13
- - Automatically rotates User Agents between requests
14
- - Tracks and updates the `Referer` header to simulate realistic request chains
13
+ - Sends a consistent macOS Chrome User-Agent and client hints that match the impersonated browser
14
+ - Tracks and updates the `Referer` header to simulate realistic request chains (following Chrome's default referrer policy, so full URLs never leak to other sites)
15
15
  - Built-in retry logic for failed requests (e.g. 429, 503, 522)
16
16
  - **Faster and Easier Parsing:**
17
17
  - Extract emails, phone numbers, images, and links from responses
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "stealth-requests"
7
- version = "2.0.6"
7
+ version = "2.2.0"
8
8
  description = "Undetected web-scraping & seamless HTML parsing in Python!"
9
9
  readme = { file = "README.md", content-type = "text/markdown" }
10
- requires-python = ">=3.10"
10
+ requires-python = ">=3.11.5"
11
11
  license = { text = "MIT" }
12
12
  authors = [
13
13
  { name = "Jacob Padilla", email = "stealth-requests@jacobpadilla.com" }
@@ -15,21 +15,20 @@ authors = [
15
15
  keywords = ["HTTP", "requests", "scraping", "browser"]
16
16
  urls = { "Homepage" = "https://github.com/jpjacobpadilla/Stealth-Requests" }
17
17
 
18
- dependencies = ["curl_cffi>=0.14.0"]
18
+ dependencies = ["curl_cffi>=0.17.0"]
19
19
 
20
20
  [project.optional-dependencies]
21
21
  parsers = [
22
- "lxml",
23
- "html2text",
24
- "beautifulsoup4"
22
+ "lxml>=6.1.0",
23
+ "html2text>=2025.4.15",
24
+ "beautifulsoup4>=4.13.0",
25
+ # Not imported directly: floor for beautifulsoup4's CSS selector engine to pick up security fixes
26
+ "soupsieve>=4.0.0",
25
27
  ]
26
28
 
27
29
  [tool.setuptools.packages.find]
28
30
  include = ["stealth_requests"]
29
31
 
30
- [tool.setuptools.package-data]
31
- stealth_requests = ["user_agents.json"]
32
-
33
32
  [tool.ruff]
34
33
  line-length = 120
35
34
 
@@ -44,8 +43,8 @@ testpaths = ["tests"]
44
43
 
45
44
  [dependency-groups]
46
45
  dev = [
47
- "lxml>=6.0.0",
48
- "pytest>=8.4.2",
46
+ "lxml>=6.1.0",
47
+ "pytest>=9.0.3",
49
48
  "pytest-asyncio>=1.2.0",
50
- "notebook>=7.4.4",
49
+ "notebook>=7.6.3",
51
50
  ]
@@ -126,7 +126,7 @@ class StealthResponse:
126
126
  if content_xpath:
127
127
  results = tree.xpath(content_xpath)
128
128
  if not results:
129
- return ""
129
+ return ''
130
130
  tree = results[0]
131
131
  html = etree.tostring(tree, pretty_print=True, method='html').decode()
132
132
 
@@ -0,0 +1,173 @@
1
+ import re
2
+ import time
3
+ import asyncio
4
+ from urllib.parse import urljoin, urlparse, urlunparse
5
+ from functools import partialmethod
6
+
7
+ from .response import StealthResponse
8
+
9
+ from curl_cffi.requests.session import Session, AsyncSession, HttpMethod
10
+
11
+
12
+ RETRY_DELAY = 2 # Seconds
13
+ RETRYABLE_STATUS_CODES = {
14
+ 408, # Request Timeout
15
+ 429, # Too Many Requests
16
+ 500, # Internal Server Error
17
+ 502, # Bad Gateway
18
+ 503, # Service Unavailable
19
+ 504, # Gateway Timeout
20
+ 520, # Cloudflare Unknown Error
21
+ 521, # Cloudflare Web Server Is Down
22
+ 522, # Cloudflare Connection Timed Out
23
+ 523, # Cloudflare Origin Is Unreachable
24
+ 524, # Cloudflare A Timeout Occurred
25
+ }
26
+
27
+
28
+ def impersonate_target() -> str:
29
+ # curl_cffi resolves 'chrome' to its newest Chrome, which may be a Windows profile.
30
+ # Prefer that version's macOS profile so curl_cffi's own headers match the macOS identity we send.
31
+ # REAL_TARGET_MAP is private, so fall back to plain 'chrome' if it ever moves.
32
+ try:
33
+ from curl_cffi.requests.impersonate import REAL_TARGET_MAP, BrowserType
34
+
35
+ macos_target = f'{REAL_TARGET_MAP["chrome"]}_macos'
36
+ return macos_target if macos_target in BrowserType.__members__ else 'chrome'
37
+ except Exception:
38
+ return 'chrome'
39
+
40
+
41
+ IMPERSONATE = impersonate_target()
42
+
43
+
44
+ def impersonated_chrome_version() -> int | None:
45
+ # REAL_TARGET_MAP is private, so fall back to None if it ever moves.
46
+ try:
47
+ from curl_cffi.requests.impersonate import REAL_TARGET_MAP
48
+
49
+ target = REAL_TARGET_MAP.get(IMPERSONATE, IMPERSONATE)
50
+ match = re.search(r'\d+', target)
51
+ return int(match.group()) if match else None
52
+ except Exception:
53
+ return None
54
+
55
+
56
+ CHROME_VERSION = impersonated_chrome_version()
57
+
58
+ # Chrome reports this token on every Mac, whatever the hardware or OS version.
59
+ PLATFORM = 'Macintosh; Intel Mac OS X 10_15_7'
60
+ PLATFORM_HINT = '"macOS"'
61
+
62
+
63
+ def identity() -> dict[str, str]:
64
+ # Without a known version, leave curl_cffi's own consistent headers alone.
65
+ if CHROME_VERSION is None:
66
+ return {}
67
+
68
+ user_agent = (
69
+ f'Mozilla/5.0 ({PLATFORM}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{CHROME_VERSION}.0.0.0 Safari/537.36'
70
+ )
71
+ return {'User-Agent': user_agent, 'Sec-CH-UA-Platform': PLATFORM_HINT}
72
+
73
+
74
+ def referer(previous_url: str | None, url: str) -> dict[str, str]:
75
+ # Follow Chrome's default strict-origin-when-cross-origin policy: the full URL (minus the query)
76
+ # only goes back to the same origin, other sites get just the origin, and HTTP gets nothing after HTTPS.
77
+ if not previous_url:
78
+ return {}
79
+
80
+ previous, target = urlparse(previous_url), urlparse(url)
81
+ if previous.scheme == 'https' and target.scheme != 'https':
82
+ return {}
83
+
84
+ # Never send credentials embedded in the URL (https://user:pass@host)
85
+ netloc = previous.netloc.rpartition('@')[2]
86
+ if (previous.scheme, netloc.lower()) == (target.scheme, target.netloc.rpartition('@')[2].lower()):
87
+ return {'Referer': urlunparse(previous._replace(netloc=netloc, query='', fragment=''))}
88
+
89
+ return {'Referer': f'{previous.scheme}://{netloc}/'}
90
+
91
+
92
+ class BaseStealthSession:
93
+ def __init__(self, **kwargs):
94
+ timeout = kwargs.pop('timeout', 30)
95
+
96
+ headers = kwargs.pop('headers', {})
97
+ for header, value in identity().items():
98
+ headers.setdefault(header, value)
99
+
100
+ self.last_request_url = None
101
+
102
+ super().__init__(impersonate=IMPERSONATE, timeout=timeout, headers=headers, **kwargs)
103
+
104
+ def _absolute_url(self, url: str) -> str:
105
+ return urljoin(self.base_url, url) if self.base_url else url
106
+
107
+
108
+ class StealthSession(BaseStealthSession, Session):
109
+ def __init__(self, *args, **kwargs):
110
+ super().__init__(*args, **kwargs)
111
+
112
+ def request(self, method: HttpMethod, url: str, *args, retry: int = 0, **kwargs) -> StealthResponse:
113
+ assert retry >= 0
114
+
115
+ url = self._absolute_url(url)
116
+ extra_headers = referer(self.last_request_url, url) | kwargs.pop('headers', {})
117
+
118
+ start = time.perf_counter()
119
+ for attempt in range(retry + 1):
120
+ resp = super().request(method, url, *args, headers=extra_headers, **kwargs)
121
+
122
+ if resp.status_code not in RETRYABLE_STATUS_CODES or attempt == retry:
123
+ break
124
+
125
+ # Retry after delay
126
+ time.sleep(RETRY_DELAY)
127
+ elapsed = time.perf_counter() - start
128
+
129
+ self.last_request_url = url
130
+
131
+ return StealthResponse(resp, elapsed)
132
+
133
+ head = partialmethod(request, 'HEAD')
134
+ get = partialmethod(request, 'GET')
135
+ post = partialmethod(request, 'POST')
136
+ put = partialmethod(request, 'PUT')
137
+ patch = partialmethod(request, 'PATCH')
138
+ delete = partialmethod(request, 'DELETE')
139
+ options = partialmethod(request, 'OPTIONS')
140
+
141
+
142
+ class AsyncStealthSession(BaseStealthSession, AsyncSession):
143
+ def __init__(self, *args, **kwargs):
144
+ super().__init__(*args, **kwargs)
145
+
146
+ async def request(self, method: HttpMethod, url: str, *args, retry: int = 0, **kwargs) -> StealthResponse:
147
+ assert retry >= 0
148
+
149
+ url = self._absolute_url(url)
150
+ extra_headers = referer(self.last_request_url, url) | kwargs.pop('headers', {})
151
+
152
+ start = time.perf_counter()
153
+ for attempt in range(retry + 1):
154
+ resp = await super().request(method, url, *args, headers=extra_headers, **kwargs)
155
+
156
+ if resp.status_code not in RETRYABLE_STATUS_CODES or attempt == retry:
157
+ break
158
+
159
+ # Retry after delay
160
+ await asyncio.sleep(RETRY_DELAY)
161
+ elapsed = time.perf_counter() - start
162
+
163
+ self.last_request_url = url
164
+
165
+ return StealthResponse(resp, elapsed)
166
+
167
+ head = partialmethod(request, 'HEAD')
168
+ get = partialmethod(request, 'GET')
169
+ post = partialmethod(request, 'POST')
170
+ put = partialmethod(request, 'PUT')
171
+ patch = partialmethod(request, 'PATCH')
172
+ delete = partialmethod(request, 'DELETE')
173
+ options = partialmethod(request, 'OPTIONS')
@@ -1,19 +1,20 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stealth-requests
3
- Version: 2.0.6
3
+ Version: 2.2.0
4
4
  Summary: Undetected web-scraping & seamless HTML parsing in Python!
5
5
  Author-email: Jacob Padilla <stealth-requests@jacobpadilla.com>
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://github.com/jpjacobpadilla/Stealth-Requests
8
8
  Keywords: HTTP,requests,scraping,browser
9
- Requires-Python: >=3.10
9
+ Requires-Python: >=3.11.5
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
- Requires-Dist: curl_cffi>=0.14.0
12
+ Requires-Dist: curl_cffi>=0.17.0
13
13
  Provides-Extra: parsers
14
- Requires-Dist: lxml; extra == "parsers"
15
- Requires-Dist: html2text; extra == "parsers"
16
- Requires-Dist: beautifulsoup4; extra == "parsers"
14
+ Requires-Dist: lxml>=6.1.0; extra == "parsers"
15
+ Requires-Dist: html2text>=2025.4.15; extra == "parsers"
16
+ Requires-Dist: beautifulsoup4>=4.13.0; extra == "parsers"
17
+ Requires-Dist: soupsieve>=4.0.0; extra == "parsers"
17
18
  Dynamic: license-file
18
19
 
19
20
  <p align="center">
@@ -22,14 +23,14 @@ Dynamic: license-file
22
23
 
23
24
  <h1 align="center">The Easiest Way to Scrape the Web</h1>
24
25
 
25
- <p align="center"><a href="https://github.com/jpjacobpadilla/stealth-requests/blob/main/LICENSE"><img src="https://img.shields.io/github/license/jpjacobpadilla/stealth-requests.svg?color=green"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.10%2B-green" alt="Python 3.10+"></a> <a href="https://pypi.org/project/stealth-requests/"><img alt="PyPI" src="https://img.shields.io/pypi/v/stealth-requests.svg?color=green"></a> <a href="https://pepy.tech/project/stealth-requests"><img alt="PyPI installs" src="https://img.shields.io/pepy/dt/stealth-requests?label=pypi%20installs&color=green"></a></p>
26
+ <p align="center"><a href="https://github.com/jpjacobpadilla/stealth-requests/blob/main/LICENSE"><img src="https://img.shields.io/github/license/jpjacobpadilla/stealth-requests.svg?color=97ca00"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.11%2B-97ca00" alt="Python 3.11+"></a> <a href="https://pypi.org/project/stealth-requests/"><img alt="PyPI" src="https://img.shields.io/pypi/v/stealth-requests.svg?color=97ca00"></a> <a href="https://pepy.tech/project/stealth-requests"><img alt="PyPI installs" src="https://static.pepy.tech/personalized-badge/stealth-requests?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=pypi%20installs"></a></p>
26
27
 
27
28
 
28
29
  ### Features
29
30
  - **Realistic HTTP Requests:**
30
31
  - Mimics Chrome browser for undetected scraping using [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/)
31
- - Automatically rotates User Agents between requests
32
- - Tracks and updates the `Referer` header to simulate realistic request chains
32
+ - Sends a consistent macOS Chrome User-Agent and client hints that match the impersonated browser
33
+ - Tracks and updates the `Referer` header to simulate realistic request chains (following Chrome's default referrer policy, so full URLs never leak to other sites)
33
34
  - Built-in retry logic for failed requests (e.g. 429, 503, 522)
34
35
  - **Faster and Easier Parsing:**
35
36
  - Extract emails, phone numbers, images, and links from responses
@@ -4,11 +4,12 @@ pyproject.toml
4
4
  stealth_requests/__init__.py
5
5
  stealth_requests/response.py
6
6
  stealth_requests/session.py
7
- stealth_requests/user_agents.json
8
7
  stealth_requests.egg-info/PKG-INFO
9
8
  stealth_requests.egg-info/SOURCES.txt
10
9
  stealth_requests.egg-info/dependency_links.txt
11
10
  stealth_requests.egg-info/requires.txt
12
11
  stealth_requests.egg-info/top_level.txt
12
+ tests/test_identity.py
13
+ tests/test_referer.py
13
14
  tests/test_requests.py
14
15
  tests/test_response.py
@@ -0,0 +1,7 @@
1
+ curl_cffi>=0.17.0
2
+
3
+ [parsers]
4
+ lxml>=6.1.0
5
+ html2text>=2025.4.15
6
+ beautifulsoup4>=4.13.0
7
+ soupsieve>=4.0.0
@@ -0,0 +1,114 @@
1
+ import re
2
+
3
+ import pytest
4
+ from stealth_requests import StealthSession, AsyncStealthSession
5
+ from stealth_requests import session as session_module
6
+ from stealth_requests.session import (
7
+ CHROME_VERSION,
8
+ IMPERSONATE,
9
+ PLATFORM,
10
+ PLATFORM_HINT,
11
+ identity,
12
+ impersonated_chrome_version,
13
+ )
14
+
15
+
16
+ URL = 'https://httpbin.org'
17
+
18
+ UA_PATTERN = re.compile(
19
+ r'Mozilla/5\.0 \((?P<platform>[^)]+)\) AppleWebKit/537\.36 '
20
+ r'\(KHTML, like Gecko\) Chrome/(?P<version>\d+)\.0\.0\.0 Safari/537\.36'
21
+ )
22
+
23
+
24
+ # --- The generated identity on its own ---
25
+
26
+
27
+ def test_impersonates_the_newest_chrome_curl_cffi_ships_on_macos():
28
+ from curl_cffi.requests.impersonate import REAL_TARGET_MAP
29
+
30
+ assert IMPERSONATE == f'{REAL_TARGET_MAP["chrome"]}_macos'
31
+
32
+
33
+ def test_version_resolves_to_the_alias_target():
34
+ from curl_cffi.requests.impersonate import REAL_TARGET_MAP
35
+
36
+ assert impersonated_chrome_version() is not None
37
+ assert REAL_TARGET_MAP['chrome'] == f'chrome{CHROME_VERSION}'
38
+
39
+
40
+ def test_platform_is_the_token_chrome_sends_on_every_mac():
41
+ assert PLATFORM == 'Macintosh; Intel Mac OS X 10_15_7'
42
+ assert PLATFORM_HINT == '"macOS"'
43
+
44
+
45
+ def test_identity_is_self_consistent():
46
+ headers = identity()
47
+ match = UA_PATTERN.fullmatch(headers['User-Agent'])
48
+
49
+ assert match, f'not a real Chrome UA: {headers["User-Agent"]}'
50
+ assert match.group('platform') == PLATFORM
51
+ assert int(match.group('version')) == CHROME_VERSION
52
+ assert headers['Sec-CH-UA-Platform'] == PLATFORM_HINT
53
+
54
+
55
+ def test_identity_is_empty_when_the_version_cannot_be_resolved(monkeypatch):
56
+ monkeypatch.setattr(session_module, 'CHROME_VERSION', None)
57
+ assert identity() == {}
58
+
59
+
60
+ # --- What actually reaches the server ---
61
+
62
+
63
+ def _assert_consistent(headers):
64
+ match = UA_PATTERN.fullmatch(headers['User-Agent'])
65
+ assert match, f'not a real Chrome UA: {headers["User-Agent"]}'
66
+ assert match.group('platform') == PLATFORM
67
+ assert headers['Sec-Ch-Ua-Platform'] == PLATFORM_HINT
68
+ # Brand hints come from curl_cffi, so this catches the UA drifting from the TLS fp.
69
+ assert f'"{CHROME_VERSION}"' in headers['Sec-Ch-Ua']
70
+
71
+
72
+ def test_sent_headers_are_consistent():
73
+ with StealthSession() as s:
74
+ _assert_consistent(s.get(f'{URL}/headers', retry=2).json()['headers'])
75
+
76
+
77
+ @pytest.mark.asyncio
78
+ async def test_async_sent_headers_are_consistent():
79
+ async with AsyncStealthSession() as s:
80
+ resp = await s.get(f'{URL}/headers', retry=2)
81
+ _assert_consistent(resp.json()['headers'])
82
+
83
+
84
+ def test_only_macintosh_user_agents_are_ever_sent():
85
+ for _ in range(5):
86
+ with StealthSession() as s:
87
+ ua = s.get(f'{URL}/headers', retry=2).json()['headers']['User-Agent']
88
+ assert 'Macintosh' in ua, ua
89
+
90
+
91
+ def test_unresolvable_version_leaves_curl_cffi_headers_intact(monkeypatch):
92
+ monkeypatch.setattr(session_module, 'CHROME_VERSION', None)
93
+
94
+ with StealthSession() as s:
95
+ headers = s.get(f'{URL}/headers', retry=2).json()['headers']
96
+
97
+ # curl_cffi's own UA, not one we built - still macOS.
98
+ assert UA_PATTERN.fullmatch(headers['User-Agent'])
99
+ assert 'Macintosh' in headers['User-Agent']
100
+
101
+
102
+ def test_identity_is_stable_within_a_session():
103
+ with StealthSession() as s:
104
+ sent = [s.get(f'{URL}/headers', retry=2).json()['headers'] for _ in range(3)]
105
+
106
+ assert len({h['User-Agent'] for h in sent}) == 1
107
+ assert len({h['Sec-Ch-Ua-Platform'] for h in sent}) == 1
108
+
109
+
110
+ def test_caller_can_override_the_user_agent():
111
+ with StealthSession(headers={'User-Agent': 'custom-agent/1.0'}) as s:
112
+ headers = s.get(f'{URL}/headers', retry=2).json()['headers']
113
+
114
+ assert headers['User-Agent'] == 'custom-agent/1.0'
@@ -0,0 +1,40 @@
1
+ import pytest
2
+ from stealth_requests import StealthSession
3
+ from stealth_requests.session import referer
4
+
5
+
6
+ def test_no_previous_request():
7
+ assert referer(None, 'https://example.com/') == {}
8
+
9
+
10
+ def test_same_origin_sends_path_without_query():
11
+ assert referer('https://example.com/a/b?token=1#frag', 'https://example.com/c') == {
12
+ 'Referer': 'https://example.com/a/b'
13
+ }
14
+
15
+
16
+ def test_cross_origin_sends_only_origin():
17
+ assert referer('https://example.com/reset/secret-token', 'https://other.com/') == {
18
+ 'Referer': 'https://example.com/'
19
+ }
20
+
21
+
22
+ def test_https_to_http_sends_nothing():
23
+ assert referer('https://example.com/a', 'http://example.com/a') == {}
24
+
25
+
26
+ def test_http_to_https_sends_origin():
27
+ assert referer('http://example.com/a', 'https://example.com/a') == {'Referer': 'http://example.com/'}
28
+
29
+
30
+ @pytest.mark.parametrize('target', ['https://example.com/next', 'https://other.com/'])
31
+ def test_credentials_never_sent(target):
32
+ header = referer('https://user:pass@example.com/a', target)['Referer']
33
+ assert 'user' not in header
34
+ assert 'pass' not in header
35
+
36
+
37
+ def test_relative_urls_resolve_against_base_url():
38
+ with StealthSession(base_url='https://example.com/api/') as s:
39
+ assert s._absolute_url('items') == 'https://example.com/api/items'
40
+ assert s._absolute_url('https://other.com/x') == 'https://other.com/x'
@@ -1,114 +0,0 @@
1
- import time
2
- import json
3
- import random
4
- import asyncio
5
- from pathlib import Path
6
- from urllib.parse import urlparse, urlunparse
7
- from functools import partialmethod
8
-
9
- from .response import StealthResponse
10
-
11
- from curl_cffi.requests.session import Session, AsyncSession, HttpMethod
12
-
13
-
14
- RETRY_DELAY = 2 # Seconds
15
- RETRYABLE_STATUS_CODES = {
16
- 408, # Request Timeout
17
- 429, # Too Many Requests
18
- 500, # Internal Server Error
19
- 502, # Bad Gateway
20
- 503, # Service Unavailable
21
- 504, # Gateway Timeout
22
- 520, # Cloudflare Unknown Error
23
- 521, # Cloudflare Web Server Is Down
24
- 522, # Cloudflare Connection Timed Out
25
- 523, # Cloudflare Origin Is Unreachable
26
- 524, # Cloudflare A Timeout Occurred
27
- }
28
-
29
-
30
- user_agents_path = Path(__file__).parent / 'user_agents.json'
31
- with user_agents_path.open() as f:
32
- user_agents = json.load(f)
33
-
34
-
35
- class BaseStealthSession:
36
- def __init__(self, **kwargs):
37
- timeout = kwargs.pop('timeout', 30)
38
-
39
- headers = kwargs.pop('headers', {})
40
- headers.setdefault('User-Agent', random.choice(user_agents))
41
-
42
- self.last_request_url = None
43
-
44
- super().__init__(impersonate='chrome136', timeout=timeout, headers=headers, **kwargs)
45
-
46
-
47
- class StealthSession(BaseStealthSession, Session):
48
- def __init__(self, *args, **kwargs):
49
- super().__init__(*args, **kwargs)
50
-
51
- def request(self, method: HttpMethod, url: str, *args, retry: int = 0, **kwargs) -> StealthResponse:
52
- assert retry >= 0
53
-
54
- referer = {'Referer': self.last_request_url} if self.last_request_url else {}
55
- extra_headers = referer | kwargs.pop('headers', {})
56
-
57
- start = time.perf_counter()
58
- for attempt in range(retry + 1):
59
- resp = super().request(method, url, *args, headers=extra_headers, **kwargs)
60
-
61
- if resp.status_code not in RETRYABLE_STATUS_CODES or attempt == retry:
62
- break
63
-
64
- # Retry after delay
65
- time.sleep(RETRY_DELAY)
66
- elapsed = time.perf_counter() - start
67
-
68
- parsed = urlparse(url)
69
- self.last_request_url = urlunparse(parsed._replace(query='', fragment=''))
70
-
71
- return StealthResponse(resp, elapsed)
72
-
73
- head = partialmethod(request, 'HEAD')
74
- get = partialmethod(request, 'GET')
75
- post = partialmethod(request, 'POST')
76
- put = partialmethod(request, 'PUT')
77
- patch = partialmethod(request, 'PATCH')
78
- delete = partialmethod(request, 'DELETE')
79
- options = partialmethod(request, 'OPTIONS')
80
-
81
-
82
- class AsyncStealthSession(BaseStealthSession, AsyncSession):
83
- def __init__(self, *args, **kwargs):
84
- super().__init__(*args, **kwargs)
85
-
86
- async def request(self, method: HttpMethod, url: str, *args, retry: int = 0, **kwargs) -> StealthResponse:
87
- assert retry >= 0
88
-
89
- referer = {'Referer': self.last_request_url} if self.last_request_url else {}
90
- extra_headers = referer | kwargs.pop('headers', {})
91
-
92
- start = time.perf_counter()
93
- for attempt in range(retry + 1):
94
- resp = await super().request(method, url, *args, headers=extra_headers, **kwargs)
95
-
96
- if resp.status_code not in RETRYABLE_STATUS_CODES or attempt == retry:
97
- break
98
-
99
- # Retry after delay
100
- await asyncio.sleep(RETRY_DELAY)
101
- elapsed = time.perf_counter() - start
102
-
103
- parsed = urlparse(url)
104
- self.last_request_url = urlunparse(parsed._replace(query='', fragment=''))
105
-
106
- return StealthResponse(resp, elapsed)
107
-
108
- head = partialmethod(request, 'HEAD')
109
- get = partialmethod(request, 'GET')
110
- post = partialmethod(request, 'POST')
111
- put = partialmethod(request, 'PUT')
112
- patch = partialmethod(request, 'PATCH')
113
- delete = partialmethod(request, 'DELETE')
114
- options = partialmethod(request, 'OPTIONS')
@@ -1,61 +0,0 @@
1
- [
2
- "Mozilla/5.0 (Macintosh; Apple M1 Max; macOS 13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.95 Safari/537.36",
3
- "Mozilla/5.0 (Macintosh; Apple M1 Max; macOS 13_5_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
4
- "Mozilla/5.0 (Macintosh; Apple M1 Pro; macOS 13_5_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
5
- "Mozilla/5.0 (Macintosh; Apple M1 Pro; macOS 14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.50 Safari/537.36",
6
- "Mozilla/5.0 (Macintosh; Apple M1 Ultra; macOS 13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.55 Safari/537.36",
7
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
8
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 11_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.58 Safari/537.36",
9
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.53 Safari/537.36",
10
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
11
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 12_7_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
12
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 12_7_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.8900.41 Safari/537.36",
13
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 13_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
14
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
15
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 13_5_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.88 Safari/537.36",
16
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 14_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
17
- "Mozilla/5.0 (Macintosh; Apple M1; macOS 14_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.8900.41 Safari/537.36",
18
- "Mozilla/5.0 (Macintosh; Apple M2 Max; macOS 13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
19
- "Mozilla/5.0 (Macintosh; Apple M2 Max; macOS 14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.51 Safari/537.36",
20
- "Mozilla/5.0 (Macintosh; Apple M2 Pro; macOS 13_5_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
21
- "Mozilla/5.0 (Macintosh; Apple M2 Pro; macOS 13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.93 Safari/537.36",
22
- "Mozilla/5.0 (Macintosh; Apple M2 Ultra; macOS 14_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.56 Safari/537.36",
23
- "Mozilla/5.0 (Macintosh; Apple M2; macOS 13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
24
- "Mozilla/5.0 (Macintosh; Apple M2; macOS 13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.54 Safari/537.36",
25
- "Mozilla/5.0 (Macintosh; Apple M2; macOS 13_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
26
- "Mozilla/5.0 (Macintosh; Apple M2; macOS 14_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
27
- "Mozilla/5.0 (Macintosh; Apple M2; macOS 14_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.84 Safari/537.36",
28
- "Mozilla/5.0 (Macintosh; Apple M2; macOS 14_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.8900.41 Safari/537.36",
29
- "Mozilla/5.0 (Macintosh; Apple M3 Max; macOS 14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
30
- "Mozilla/5.0 (Macintosh; Apple M3 Pro; macOS 13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.57 Safari/537.36",
31
- "Mozilla/5.0 (Macintosh; Apple M3 Pro; macOS 14_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
32
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
33
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.8900.41 Safari/537.36",
34
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
35
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.99 Safari/537.36",
36
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.52 Safari/537.36",
37
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
38
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.48 Safari/537.36",
39
- "Mozilla/5.0 (Macintosh; Apple M3; macOS 14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.8900.41 Safari/537.36",
40
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.64 Safari/537.36",
41
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.63 Safari/537.36",
42
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
43
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.62 Safari/537.36",
44
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
45
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
46
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.61 Safari/537.36",
47
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
48
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
49
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.60 Safari/537.36",
50
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
51
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.85 Safari/537.36",
52
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
53
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
54
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
55
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.49 Safari/537.36",
56
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.59 Safari/537.36",
57
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.81 Safari/537.36",
58
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.97 Safari/537.36",
59
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.66 Safari/537.36",
60
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.7103.65 Safari/537.36"
61
- ]
@@ -1,6 +0,0 @@
1
- curl_cffi>=0.14.0
2
-
3
- [parsers]
4
- lxml
5
- html2text
6
- beautifulsoup4