stealth-requests 2.0.4__tar.gz → 2.0.6__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.
@@ -1,21 +1,19 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stealth-requests
3
- Version: 2.0.4
3
+ Version: 2.0.6
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.9
9
+ Requires-Python: >=3.10
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
- Requires-Dist: curl_cffi
12
+ Requires-Dist: curl_cffi>=0.14.0
13
13
  Provides-Extra: parsers
14
14
  Requires-Dist: lxml; extra == "parsers"
15
15
  Requires-Dist: html2text; extra == "parsers"
16
16
  Requires-Dist: beautifulsoup4; extra == "parsers"
17
- Provides-Extra: dev
18
- Requires-Dist: notebook>=7.4.4; extra == "dev"
19
17
  Dynamic: license-file
20
18
 
21
19
  <p align="center">
@@ -24,12 +22,12 @@ Dynamic: license-file
24
22
 
25
23
  <h1 align="center">The Easiest Way to Scrape the Web</h1>
26
24
 
27
- <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.9%2B-green" alt="Python 3.8+"></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>
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>
28
26
 
29
27
 
30
28
  ### Features
31
29
  - **Realistic HTTP Requests:**
32
- - Mimics the Chrome browser for undetected scraping using the [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/) package
30
+ - Mimics Chrome browser for undetected scraping using [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/)
33
31
  - Automatically rotates User Agents between requests
34
32
  - Tracks and updates the `Referer` header to simulate realistic request chains
35
33
  - Built-in retry logic for failed requests (e.g. 429, 503, 522)
@@ -53,6 +51,7 @@ $ pip install stealth_requests
53
51
  - [Sending Requests With Asyncio](#sending-requests-with-asyncio)
54
52
  - [Accessing Page Metadata](#accessing-page-metadata)
55
53
  - [Extracting Emails, Phone Numbers, Images, and Links](#extracting-emails-phone-numbers-images-and-links)
54
+ - [Extracting HTML Tables](#extracting-html-tables)
56
55
  - [More Parsing Options](#more-parsing-options)
57
56
  - [Converting Responses to Markdown](#converting-responses-to-markdown)
58
57
  - [Using Proxies](#using-proxies)
@@ -147,6 +146,33 @@ print(resp.links)
147
146
  ```
148
147
 
149
148
 
149
+ ### Extracting HTML Tables
150
+
151
+ The `StealthResponse` object can parse HTML tables into dictionaries, where each key is a column header and the value is a list of that column's cell values.
152
+
153
+ For example, given a page with this table:
154
+
155
+ | Name | Age |
156
+ |-------|-----|
157
+ | Jacob | 30 |
158
+ | Jake | 25 |
159
+
160
+ You can extract it like this:
161
+
162
+ ```python
163
+ import stealth_requests as requests
164
+
165
+ resp = requests.get('https://link-here.com')
166
+
167
+ # Each table becomes a dict: {column_name: [values]}
168
+ for table in resp.tables:
169
+ print(table)
170
+ # Output: {'Name': ['Jacob', 'Jake'], 'Age': ['30', '25']}
171
+ ```
172
+
173
+ Tables without recognizable headers are automatically skipped.
174
+
175
+
150
176
  ### More Parsing Options
151
177
 
152
178
  To make parsing HTML faster, I've also added two popular parsing packages to Stealth-Requests: Lxml and BeautifulSoup4. To use these add-ons, you need to install the `parsers` extra:
@@ -4,12 +4,12 @@
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.9%2B-green" alt="Python 3.8+"></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=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>
8
8
 
9
9
 
10
10
  ### Features
11
11
  - **Realistic HTTP Requests:**
12
- - Mimics the Chrome browser for undetected scraping using the [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/) package
12
+ - Mimics Chrome browser for undetected scraping using [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/)
13
13
  - Automatically rotates User Agents between requests
14
14
  - Tracks and updates the `Referer` header to simulate realistic request chains
15
15
  - Built-in retry logic for failed requests (e.g. 429, 503, 522)
@@ -33,6 +33,7 @@ $ pip install stealth_requests
33
33
  - [Sending Requests With Asyncio](#sending-requests-with-asyncio)
34
34
  - [Accessing Page Metadata](#accessing-page-metadata)
35
35
  - [Extracting Emails, Phone Numbers, Images, and Links](#extracting-emails-phone-numbers-images-and-links)
36
+ - [Extracting HTML Tables](#extracting-html-tables)
36
37
  - [More Parsing Options](#more-parsing-options)
37
38
  - [Converting Responses to Markdown](#converting-responses-to-markdown)
38
39
  - [Using Proxies](#using-proxies)
@@ -127,6 +128,33 @@ print(resp.links)
127
128
  ```
128
129
 
129
130
 
131
+ ### Extracting HTML Tables
132
+
133
+ The `StealthResponse` object can parse HTML tables into dictionaries, where each key is a column header and the value is a list of that column's cell values.
134
+
135
+ For example, given a page with this table:
136
+
137
+ | Name | Age |
138
+ |-------|-----|
139
+ | Jacob | 30 |
140
+ | Jake | 25 |
141
+
142
+ You can extract it like this:
143
+
144
+ ```python
145
+ import stealth_requests as requests
146
+
147
+ resp = requests.get('https://link-here.com')
148
+
149
+ # Each table becomes a dict: {column_name: [values]}
150
+ for table in resp.tables:
151
+ print(table)
152
+ # Output: {'Name': ['Jacob', 'Jake'], 'Age': ['30', '25']}
153
+ ```
154
+
155
+ Tables without recognizable headers are automatically skipped.
156
+
157
+
130
158
  ### More Parsing Options
131
159
 
132
160
  To make parsing HTML faster, I've also added two popular parsing packages to Stealth-Requests: Lxml and BeautifulSoup4. To use these add-ons, you need to install the `parsers` extra:
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "stealth-requests"
7
- version = "2.0.4"
7
+ version = "2.0.6"
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.9"
10
+ requires-python = ">=3.10"
11
11
  license = { text = "MIT" }
12
12
  authors = [
13
13
  { name = "Jacob Padilla", email = "stealth-requests@jacobpadilla.com" }
@@ -15,7 +15,7 @@ authors = [
15
15
  keywords = ["HTTP", "requests", "scraping", "browser"]
16
16
  urls = { "Homepage" = "https://github.com/jpjacobpadilla/Stealth-Requests" }
17
17
 
18
- dependencies = ["curl_cffi"]
18
+ dependencies = ["curl_cffi>=0.14.0"]
19
19
 
20
20
  [project.optional-dependencies]
21
21
  parsers = [
@@ -23,9 +23,6 @@ parsers = [
23
23
  "html2text",
24
24
  "beautifulsoup4"
25
25
  ]
26
- dev = [
27
- "notebook>=7.4.4",
28
- ]
29
26
 
30
27
  [tool.setuptools.packages.find]
31
28
  include = ["stealth_requests"]
@@ -40,4 +37,15 @@ line-length = 120
40
37
  select = ["I", "TID"]
41
38
 
42
39
  [tool.ruff.format]
43
- quote-style = "single"
40
+ quote-style = "single"
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+
45
+ [dependency-groups]
46
+ dev = [
47
+ "lxml>=6.0.0",
48
+ "pytest>=8.4.2",
49
+ "pytest-asyncio>=1.2.0",
50
+ "notebook>=7.4.4",
51
+ ]
@@ -26,19 +26,21 @@ PARSER_IMPORT_SOLUTION = "Install it using 'pip install stealth-requests[parsers
26
26
 
27
27
 
28
28
  class StealthResponse:
29
- def __init__(self, resp):
29
+ def __init__(self, resp, elapsed):
30
30
  self._response = resp
31
+ self._elapsed = elapsed
31
32
 
32
33
  self._tree: HtmlElement | None = None
33
34
  self._important_meta_tags: Metadata | None = None
34
35
  self._links: tuple[str] = tuple()
35
36
  self._images: tuple[str] = tuple()
37
+ self._tables: list[dict[str, list[str]]] | None = None
36
38
 
37
39
  def __getattr__(self, name):
38
40
  return getattr(self._response, name)
39
41
 
40
42
  def __repr__(self):
41
- return f'<StealthResponse [Status: {self._response.status_code} Elapsed Time: {self._response.elapsed:.2f} seconds]>'
43
+ return f'<StealthResponse [Status: {self._response.status_code} Elapsed Time: {self._elapsed:.2f} seconds]>'
42
44
 
43
45
  def _get_tree(self) -> HtmlElement:
44
46
  try:
@@ -122,7 +124,10 @@ class StealthResponse:
122
124
 
123
125
  tree = self.tree()
124
126
  if content_xpath:
125
- tree = tree.xpath(content_xpath)[0]
127
+ results = tree.xpath(content_xpath)
128
+ if not results:
129
+ return ""
130
+ tree = results[0]
126
131
  html = etree.tostring(tree, pretty_print=True, method='html').decode()
127
132
 
128
133
  return text_maker.handle(html)
@@ -155,6 +160,48 @@ class StealthResponse:
155
160
  self._links = self._parse_links('a')
156
161
  return self._links
157
162
 
163
+ @staticmethod
164
+ def _parse_table(table_element) -> dict[str, list[str]] | None:
165
+ header_row = table_element.xpath('.//thead/tr[1] | .//tr[th][1]')
166
+ if not header_row:
167
+ return None
168
+
169
+ headers = [th.text_content().strip() for th in header_row[0].xpath('./th | ./td')]
170
+ if not headers or all(h == '' for h in headers):
171
+ return None
172
+
173
+ body_rows = table_element.xpath('.//tbody/tr')
174
+ if not body_rows:
175
+ all_rows = table_element.xpath('.//tr')
176
+ # Skip the header row
177
+ body_rows = [r for r in all_rows if r is not header_row[0]]
178
+
179
+ result = {header: [] for header in headers}
180
+ for row in body_rows:
181
+ cells = row.xpath('./td | ./th')
182
+ for i, header in enumerate(headers):
183
+ value = cells[i].text_content().strip() if i < len(cells) else ''
184
+ result[header].append(value)
185
+
186
+ return result
187
+
188
+ @property
189
+ def tables(self) -> list[dict[str, list[str]]]:
190
+ if self._tables is not None:
191
+ return self._tables
192
+
193
+ parsed = []
194
+ for table in self.tree().xpath('//table'):
195
+ try:
196
+ result = self._parse_table(table)
197
+ if result is not None:
198
+ parsed.append(result)
199
+ except Exception:
200
+ continue
201
+
202
+ self._tables = parsed
203
+ return self._tables
204
+
158
205
  @property
159
206
  def emails(self) -> tuple[str]:
160
207
  content = self._response.text
@@ -41,7 +41,7 @@ class BaseStealthSession:
41
41
 
42
42
  self.last_request_url = None
43
43
 
44
- super().__init__(impersonate='chrome', timeout=timeout, headers=headers, **kwargs)
44
+ super().__init__(impersonate='chrome136', timeout=timeout, headers=headers, **kwargs)
45
45
 
46
46
 
47
47
  class StealthSession(BaseStealthSession, Session):
@@ -54,20 +54,21 @@ class StealthSession(BaseStealthSession, Session):
54
54
  referer = {'Referer': self.last_request_url} if self.last_request_url else {}
55
55
  extra_headers = referer | kwargs.pop('headers', {})
56
56
 
57
+ start = time.perf_counter()
57
58
  for attempt in range(retry + 1):
58
59
  resp = super().request(method, url, *args, headers=extra_headers, **kwargs)
59
- response = StealthResponse(resp)
60
60
 
61
61
  if resp.status_code not in RETRYABLE_STATUS_CODES or attempt == retry:
62
62
  break
63
63
 
64
64
  # Retry after delay
65
65
  time.sleep(RETRY_DELAY)
66
+ elapsed = time.perf_counter() - start
66
67
 
67
68
  parsed = urlparse(url)
68
69
  self.last_request_url = urlunparse(parsed._replace(query='', fragment=''))
69
70
 
70
- return response
71
+ return StealthResponse(resp, elapsed)
71
72
 
72
73
  head = partialmethod(request, 'HEAD')
73
74
  get = partialmethod(request, 'GET')
@@ -88,20 +89,21 @@ class AsyncStealthSession(BaseStealthSession, AsyncSession):
88
89
  referer = {'Referer': self.last_request_url} if self.last_request_url else {}
89
90
  extra_headers = referer | kwargs.pop('headers', {})
90
91
 
92
+ start = time.perf_counter()
91
93
  for attempt in range(retry + 1):
92
94
  resp = await super().request(method, url, *args, headers=extra_headers, **kwargs)
93
- response = StealthResponse(resp)
94
95
 
95
96
  if resp.status_code not in RETRYABLE_STATUS_CODES or attempt == retry:
96
97
  break
97
98
 
98
99
  # Retry after delay
99
100
  await asyncio.sleep(RETRY_DELAY)
101
+ elapsed = time.perf_counter() - start
100
102
 
101
103
  parsed = urlparse(url)
102
104
  self.last_request_url = urlunparse(parsed._replace(query='', fragment=''))
103
105
 
104
- return response
106
+ return StealthResponse(resp, elapsed)
105
107
 
106
108
  head = partialmethod(request, 'HEAD')
107
109
  get = partialmethod(request, 'GET')
@@ -1,21 +1,19 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stealth-requests
3
- Version: 2.0.4
3
+ Version: 2.0.6
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.9
9
+ Requires-Python: >=3.10
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
- Requires-Dist: curl_cffi
12
+ Requires-Dist: curl_cffi>=0.14.0
13
13
  Provides-Extra: parsers
14
14
  Requires-Dist: lxml; extra == "parsers"
15
15
  Requires-Dist: html2text; extra == "parsers"
16
16
  Requires-Dist: beautifulsoup4; extra == "parsers"
17
- Provides-Extra: dev
18
- Requires-Dist: notebook>=7.4.4; extra == "dev"
19
17
  Dynamic: license-file
20
18
 
21
19
  <p align="center">
@@ -24,12 +22,12 @@ Dynamic: license-file
24
22
 
25
23
  <h1 align="center">The Easiest Way to Scrape the Web</h1>
26
24
 
27
- <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.9%2B-green" alt="Python 3.8+"></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>
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>
28
26
 
29
27
 
30
28
  ### Features
31
29
  - **Realistic HTTP Requests:**
32
- - Mimics the Chrome browser for undetected scraping using the [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/) package
30
+ - Mimics Chrome browser for undetected scraping using [curl_cffi](https://curl-cffi.readthedocs.io/en/latest/)
33
31
  - Automatically rotates User Agents between requests
34
32
  - Tracks and updates the `Referer` header to simulate realistic request chains
35
33
  - Built-in retry logic for failed requests (e.g. 429, 503, 522)
@@ -53,6 +51,7 @@ $ pip install stealth_requests
53
51
  - [Sending Requests With Asyncio](#sending-requests-with-asyncio)
54
52
  - [Accessing Page Metadata](#accessing-page-metadata)
55
53
  - [Extracting Emails, Phone Numbers, Images, and Links](#extracting-emails-phone-numbers-images-and-links)
54
+ - [Extracting HTML Tables](#extracting-html-tables)
56
55
  - [More Parsing Options](#more-parsing-options)
57
56
  - [Converting Responses to Markdown](#converting-responses-to-markdown)
58
57
  - [Using Proxies](#using-proxies)
@@ -147,6 +146,33 @@ print(resp.links)
147
146
  ```
148
147
 
149
148
 
149
+ ### Extracting HTML Tables
150
+
151
+ The `StealthResponse` object can parse HTML tables into dictionaries, where each key is a column header and the value is a list of that column's cell values.
152
+
153
+ For example, given a page with this table:
154
+
155
+ | Name | Age |
156
+ |-------|-----|
157
+ | Jacob | 30 |
158
+ | Jake | 25 |
159
+
160
+ You can extract it like this:
161
+
162
+ ```python
163
+ import stealth_requests as requests
164
+
165
+ resp = requests.get('https://link-here.com')
166
+
167
+ # Each table becomes a dict: {column_name: [values]}
168
+ for table in resp.tables:
169
+ print(table)
170
+ # Output: {'Name': ['Jacob', 'Jake'], 'Age': ['30', '25']}
171
+ ```
172
+
173
+ Tables without recognizable headers are automatically skipped.
174
+
175
+
150
176
  ### More Parsing Options
151
177
 
152
178
  To make parsing HTML faster, I've also added two popular parsing packages to Stealth-Requests: Lxml and BeautifulSoup4. To use these add-ons, you need to install the `parsers` extra:
@@ -9,4 +9,6 @@ stealth_requests.egg-info/PKG-INFO
9
9
  stealth_requests.egg-info/SOURCES.txt
10
10
  stealth_requests.egg-info/dependency_links.txt
11
11
  stealth_requests.egg-info/requires.txt
12
- stealth_requests.egg-info/top_level.txt
12
+ stealth_requests.egg-info/top_level.txt
13
+ tests/test_requests.py
14
+ tests/test_response.py
@@ -1,7 +1,4 @@
1
- curl_cffi
2
-
3
- [dev]
4
- notebook>=7.4.4
1
+ curl_cffi>=0.14.0
5
2
 
6
3
  [parsers]
7
4
  lxml
@@ -0,0 +1,112 @@
1
+ import re
2
+
3
+ import pytest
4
+ import stealth_requests as stealth
5
+ from stealth_requests import StealthSession, AsyncStealthSession
6
+
7
+
8
+ URL = 'https://httpbin.org'
9
+
10
+
11
+ # --- Sync ---
12
+
13
+
14
+ def test_get():
15
+ resp = stealth.get(f'{URL}/get')
16
+ assert resp.status_code == 200
17
+
18
+
19
+ def test_post():
20
+ resp = stealth.post(f'{URL}/post', json={'key': 'value'})
21
+ assert resp.status_code == 200
22
+ assert resp.json()['json']['key'] == 'value'
23
+
24
+
25
+ def test_session_get():
26
+ with StealthSession() as s:
27
+ resp = s.get(f'{URL}/get')
28
+ assert resp.status_code == 200
29
+
30
+
31
+ def test_session_sets_referer():
32
+ with StealthSession() as s:
33
+ s.get(f'{URL}/get')
34
+ resp = s.get(f'{URL}/headers')
35
+ headers = resp.json()['headers']
36
+ assert f'{URL}/get' in headers.get('Referer', '')
37
+
38
+
39
+ def test_session_has_user_agent():
40
+ with StealthSession() as s:
41
+ resp = s.get(f'{URL}/headers')
42
+ headers = resp.json()['headers']
43
+ assert 'User-Agent' in headers
44
+ assert headers['User-Agent'] != ''
45
+
46
+
47
+ # --- Async ---
48
+
49
+
50
+ @pytest.mark.asyncio
51
+ async def test_async_get():
52
+ async with AsyncStealthSession() as s:
53
+ resp = await s.get(f'{URL}/get')
54
+ assert resp.status_code == 200
55
+
56
+
57
+ @pytest.mark.asyncio
58
+ async def test_async_post():
59
+ async with AsyncStealthSession() as s:
60
+ resp = await s.post(f'{URL}/post', json={'hello': 'world'})
61
+ assert resp.status_code == 200
62
+ assert resp.json()['json']['hello'] == 'world'
63
+
64
+
65
+ @pytest.mark.asyncio
66
+ async def test_async_session_sets_referer():
67
+ async with AsyncStealthSession() as s:
68
+ await s.get(f'{URL}/get')
69
+ resp = await s.get(f'{URL}/headers')
70
+ headers = resp.json()['headers']
71
+ assert f'{URL}/get' in headers.get('Referer', '')
72
+
73
+
74
+ # --- Response features (using a real HTML page) ---
75
+
76
+ HTML_URL = 'https://books.toscrape.com'
77
+
78
+
79
+ def test_repr():
80
+ resp = stealth.get(f'{URL}/get')
81
+ assert re.fullmatch(r'<StealthResponse \[Status: \d+ Elapsed Time: \d+\.\d+ seconds\]>', repr(resp))
82
+
83
+
84
+ def test_links():
85
+ resp = stealth.get(HTML_URL)
86
+ assert isinstance(resp.links, tuple)
87
+ assert len(resp.links) > 0
88
+ assert all(isinstance(link, str) for link in resp.links)
89
+
90
+
91
+ def test_images():
92
+ resp = stealth.get(HTML_URL)
93
+ assert isinstance(resp.images, tuple)
94
+ assert len(resp.images) > 0
95
+ assert all(isinstance(img, str) for img in resp.images)
96
+
97
+
98
+ def test_emails():
99
+ resp = stealth.get(f'{URL}/html')
100
+ assert isinstance(resp.emails, tuple)
101
+
102
+
103
+ def test_phone_numbers():
104
+ resp = stealth.get(f'{URL}/html')
105
+ assert isinstance(resp.phone_numbers, tuple)
106
+
107
+
108
+ def test_metadata():
109
+ resp = stealth.get(HTML_URL)
110
+ meta = resp.meta
111
+ assert meta.title is not None
112
+ assert isinstance(meta.title, str)
@@ -0,0 +1,475 @@
1
+ from types import SimpleNamespace
2
+
3
+ from stealth_requests.response import StealthResponse
4
+
5
+
6
+ def make_response(html, url='https://example.com'):
7
+ """Create a StealthResponse from raw HTML and a fake URL."""
8
+ raw = SimpleNamespace(
9
+ content=html.encode(),
10
+ text=html,
11
+ url=url,
12
+ status_code=200,
13
+ )
14
+ return StealthResponse(raw, elapsed=0.1)
15
+
16
+
17
+ # ── Tables ──────────────────────────────────────────────────────────────
18
+
19
+
20
+ class TestTables:
21
+ def test_basic_thead_tbody(self):
22
+ html = """
23
+ <html><body>
24
+ <table>
25
+ <thead><tr><th>Name</th><th>Age</th></tr></thead>
26
+ <tbody>
27
+ <tr><td>Alice</td><td>30</td></tr>
28
+ <tr><td>Bob</td><td>25</td></tr>
29
+ </tbody>
30
+ </table>
31
+ </body></html>
32
+ """
33
+ resp = make_response(html)
34
+ assert resp.tables == [{'Name': ['Alice', 'Bob'], 'Age': ['30', '25']}]
35
+
36
+ def test_table_without_thead(self):
37
+ html = """
38
+ <html><body>
39
+ <table>
40
+ <tr><th>Color</th><th>Hex</th></tr>
41
+ <tr><td>Red</td><td>#FF0000</td></tr>
42
+ <tr><td>Blue</td><td>#0000FF</td></tr>
43
+ </table>
44
+ </body></html>
45
+ """
46
+ resp = make_response(html)
47
+ assert resp.tables == [{'Color': ['Red', 'Blue'], 'Hex': ['#FF0000', '#0000FF']}]
48
+
49
+ def test_multiple_tables(self):
50
+ html = """
51
+ <html><body>
52
+ <table>
53
+ <thead><tr><th>X</th></tr></thead>
54
+ <tbody><tr><td>1</td></tr></tbody>
55
+ </table>
56
+ <table>
57
+ <thead><tr><th>Y</th></tr></thead>
58
+ <tbody><tr><td>2</td></tr></tbody>
59
+ </table>
60
+ </body></html>
61
+ """
62
+ resp = make_response(html)
63
+ assert len(resp.tables) == 2
64
+ assert resp.tables[0] == {'X': ['1']}
65
+ assert resp.tables[1] == {'Y': ['2']}
66
+
67
+ def test_table_no_headers_skipped(self):
68
+ html = """
69
+ <html><body>
70
+ <table>
71
+ <tr><td>no</td><td>headers</td></tr>
72
+ <tr><td>at</td><td>all</td></tr>
73
+ </table>
74
+ </body></html>
75
+ """
76
+ resp = make_response(html)
77
+ assert resp.tables == []
78
+
79
+ def test_table_empty_headers_skipped(self):
80
+ html = """
81
+ <html><body>
82
+ <table>
83
+ <thead><tr><th></th><th></th></tr></thead>
84
+ <tbody><tr><td>a</td><td>b</td></tr></tbody>
85
+ </table>
86
+ </body></html>
87
+ """
88
+ resp = make_response(html)
89
+ assert resp.tables == []
90
+
91
+ def test_row_with_fewer_cells(self):
92
+ html = """
93
+ <html><body>
94
+ <table>
95
+ <thead><tr><th>A</th><th>B</th><th>C</th></tr></thead>
96
+ <tbody>
97
+ <tr><td>1</td><td>2</td></tr>
98
+ </tbody>
99
+ </table>
100
+ </body></html>
101
+ """
102
+ resp = make_response(html)
103
+ assert resp.tables == [{'A': ['1'], 'B': ['2'], 'C': ['']}]
104
+
105
+ def test_tables_cached(self):
106
+ html = """
107
+ <html><body>
108
+ <table>
109
+ <thead><tr><th>Col</th></tr></thead>
110
+ <tbody><tr><td>val</td></tr></tbody>
111
+ </table>
112
+ </body></html>
113
+ """
114
+ resp = make_response(html)
115
+ first = resp.tables
116
+ second = resp.tables
117
+ assert first is second
118
+
119
+ def test_no_tables(self):
120
+ html = '<html><body><p>No tables here</p></body></html>'
121
+ resp = make_response(html)
122
+ assert resp.tables == []
123
+
124
+ def test_nested_elements_in_cells(self):
125
+ html = """
126
+ <html><body>
127
+ <table>
128
+ <thead><tr><th>Link</th><th>Info</th></tr></thead>
129
+ <tbody>
130
+ <tr><td><a href="/page">Click here</a></td><td><strong>Bold</strong> text</td></tr>
131
+ </tbody>
132
+ </table>
133
+ </body></html>
134
+ """
135
+ resp = make_response(html)
136
+ assert resp.tables == [{'Link': ['Click here'], 'Info': ['Bold text']}]
137
+
138
+ def test_whitespace_in_cells(self):
139
+ html = """
140
+ <html><body>
141
+ <table>
142
+ <thead><tr><th> Name </th><th> Value </th></tr></thead>
143
+ <tbody>
144
+ <tr><td> foo </td><td> bar </td></tr>
145
+ </tbody>
146
+ </table>
147
+ </body></html>
148
+ """
149
+ resp = make_response(html)
150
+ assert resp.tables == [{'Name': ['foo'], 'Value': ['bar']}]
151
+
152
+ def test_single_column_table(self):
153
+ html = """
154
+ <html><body>
155
+ <table>
156
+ <thead><tr><th>Items</th></tr></thead>
157
+ <tbody>
158
+ <tr><td>Apple</td></tr>
159
+ <tr><td>Banana</td></tr>
160
+ <tr><td>Cherry</td></tr>
161
+ </tbody>
162
+ </table>
163
+ </body></html>
164
+ """
165
+ resp = make_response(html)
166
+ assert resp.tables == [{'Items': ['Apple', 'Banana', 'Cherry']}]
167
+
168
+ def test_many_columns(self):
169
+ html = """
170
+ <html><body>
171
+ <table>
172
+ <thead><tr><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th></tr></thead>
173
+ <tbody>
174
+ <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>
175
+ <tr><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr>
176
+ </tbody>
177
+ </table>
178
+ </body></html>
179
+ """
180
+ resp = make_response(html)
181
+ assert resp.tables == [{'A': ['1', '6'], 'B': ['2', '7'], 'C': ['3', '8'], 'D': ['4', '9'], 'E': ['5', '10']}]
182
+
183
+ def test_empty_tbody(self):
184
+ html = """
185
+ <html><body>
186
+ <table>
187
+ <thead><tr><th>Name</th><th>Age</th></tr></thead>
188
+ <tbody></tbody>
189
+ </table>
190
+ </body></html>
191
+ """
192
+ resp = make_response(html)
193
+ assert resp.tables == [{'Name': [], 'Age': []}]
194
+
195
+ def test_mixed_valid_and_invalid_tables(self):
196
+ html = """
197
+ <html><body>
198
+ <table>
199
+ <thead><tr><th>Good</th></tr></thead>
200
+ <tbody><tr><td>yes</td></tr></tbody>
201
+ </table>
202
+ <table>
203
+ <tr><td>no</td><td>headers</td></tr>
204
+ </table>
205
+ <table>
206
+ <thead><tr><th>Also Good</th></tr></thead>
207
+ <tbody><tr><td>yep</td></tr></tbody>
208
+ </table>
209
+ </body></html>
210
+ """
211
+ resp = make_response(html)
212
+ assert len(resp.tables) == 2
213
+ assert resp.tables[0] == {'Good': ['yes']}
214
+ assert resp.tables[1] == {'Also Good': ['yep']}
215
+
216
+ def test_row_with_extra_cells(self):
217
+ html = """
218
+ <html><body>
219
+ <table>
220
+ <thead><tr><th>A</th><th>B</th></tr></thead>
221
+ <tbody>
222
+ <tr><td>1</td><td>2</td><td>3</td></tr>
223
+ </tbody>
224
+ </table>
225
+ </body></html>
226
+ """
227
+ resp = make_response(html)
228
+ # Extra cells beyond the header count are ignored
229
+ assert resp.tables == [{'A': ['1'], 'B': ['2']}]
230
+
231
+ def test_special_characters_in_cells(self):
232
+ html = """
233
+ <html><body>
234
+ <table>
235
+ <thead><tr><th>Symbol</th><th>Price</th></tr></thead>
236
+ <tbody>
237
+ <tr><td>AT&amp;T</td><td>$25.50</td></tr>
238
+ <tr><td>O'Reilly</td><td>&euro;30.00</td></tr>
239
+ </tbody>
240
+ </table>
241
+ </body></html>
242
+ """
243
+ resp = make_response(html)
244
+ assert resp.tables[0]['Symbol'] == ['AT&T', "O'Reilly"]
245
+ assert resp.tables[0]['Price'] == ['$25.50', '\u20ac30.00']
246
+
247
+ def test_nested_table_parsed_separately(self):
248
+ html = """
249
+ <html><body>
250
+ <table>
251
+ <thead><tr><th>Outer</th></tr></thead>
252
+ <tbody>
253
+ <tr><td>
254
+ <table>
255
+ <thead><tr><th>Inner</th></tr></thead>
256
+ <tbody><tr><td>nested</td></tr></tbody>
257
+ </table>
258
+ </td></tr>
259
+ </tbody>
260
+ </table>
261
+ </body></html>
262
+ """
263
+ resp = make_response(html)
264
+ # Both the outer and inner table should be parsed
265
+ assert len(resp.tables) == 2
266
+ inner = next(t for t in resp.tables if 'Inner' in t)
267
+ assert inner == {'Inner': ['nested']}
268
+
269
+ def test_malformed_missing_td_skipped(self):
270
+ html = """
271
+ <html><body>
272
+ <table>
273
+ <thead><tr><th>A</th><th>B</th></tr></thead>
274
+ <tbody>
275
+ <tr></tr>
276
+ </tbody>
277
+ </table>
278
+ </body></html>
279
+ """
280
+ resp = make_response(html)
281
+ # Row with zero cells — both columns get empty strings
282
+ assert resp.tables == [{'A': [''], 'B': ['']}]
283
+
284
+ def test_malformed_empty_table_tag(self):
285
+ html = '<html><body><table></table></body></html>'
286
+ resp = make_response(html)
287
+ assert resp.tables == []
288
+
289
+ def test_malformed_thead_no_th(self):
290
+ html = """
291
+ <html><body>
292
+ <table>
293
+ <thead><tr></tr></thead>
294
+ <tbody><tr><td>data</td></tr></tbody>
295
+ </table>
296
+ </body></html>
297
+ """
298
+ resp = make_response(html)
299
+ assert resp.tables == []
300
+
301
+ def test_malformed_unclosed_tags(self):
302
+ html = """
303
+ <html><body>
304
+ <table>
305
+ <thead><tr><th>X</th><th>Y</th></tr></thead>
306
+ <tbody>
307
+ <tr><td>1<td>2</tr>
308
+ <tr><td>3</td><td>4</td></tr>
309
+ </tbody>
310
+ </table>
311
+ </body></html>
312
+ """
313
+ resp = make_response(html)
314
+ # lxml fixes up the broken HTML — table should still parse
315
+ assert len(resp.tables) == 1
316
+ assert resp.tables[0]['X'] == ['1', '3']
317
+
318
+ def test_malformed_only_thead_no_tbody(self):
319
+ html = """
320
+ <html><body>
321
+ <table>
322
+ <thead><tr><th>Header</th></tr></thead>
323
+ </table>
324
+ </body></html>
325
+ """
326
+ resp = make_response(html)
327
+ # Headers exist but no data rows
328
+ assert resp.tables == [{'Header': []}]
329
+
330
+
331
+ # ── Metadata ────────────────────────────────────────────────────────────
332
+
333
+
334
+ class TestMetadata:
335
+ def test_all_meta_fields(self):
336
+ html = """
337
+ <html><head>
338
+ <title>Test Page</title>
339
+ <meta name="description" content="A test page">
340
+ <meta property="og:image" content="https://example.com/img.png">
341
+ <meta name="author" content="Alice">
342
+ <meta name="keywords" content="python, scraping">
343
+ <meta name="twitter:site" content="@alice">
344
+ <meta name="robots" content="index, follow">
345
+ <link rel="canonical" href="https://example.com/canonical">
346
+ </head><body></body></html>
347
+ """
348
+ resp = make_response(html)
349
+ meta = resp.meta
350
+ assert meta.title == 'Test Page'
351
+ assert meta.description == 'A test page'
352
+ assert meta.thumbnail == 'https://example.com/img.png'
353
+ assert meta.author == 'Alice'
354
+ assert meta.keywords == ('python', 'scraping')
355
+ assert meta.twitter_handle == '@alice'
356
+ assert meta.robots == ('index', 'follow')
357
+ assert meta.canonical == 'https://example.com/canonical'
358
+
359
+ def test_missing_meta_fields(self):
360
+ html = '<html><head></head><body></body></html>'
361
+ resp = make_response(html)
362
+ meta = resp.meta
363
+ assert meta.title is None
364
+ assert meta.description is None
365
+ assert meta.thumbnail is None
366
+ assert meta.author is None
367
+ assert meta.keywords is None
368
+ assert meta.twitter_handle is None
369
+ assert meta.robots is None
370
+ assert meta.canonical is None
371
+
372
+ def test_meta_cached(self):
373
+ html = '<html><head><title>Hi</title></head><body></body></html>'
374
+ resp = make_response(html)
375
+ first = resp.meta
376
+ second = resp.meta
377
+ assert first is second
378
+
379
+
380
+ # ── Emails ──────────────────────────────────────────────────────────────
381
+
382
+
383
+ class TestEmails:
384
+ def test_extracts_emails(self):
385
+ html = '<html><body>Contact us at info@example.com or support@test.org</body></html>'
386
+ resp = make_response(html)
387
+ assert set(resp.emails) == {'info@example.com', 'support@test.org'}
388
+
389
+ def test_no_emails(self):
390
+ html = '<html><body>No emails here</body></html>'
391
+ resp = make_response(html)
392
+ assert resp.emails == ()
393
+
394
+ def test_deduplicates_emails(self):
395
+ html = '<html><body>a@b.com and a@b.com again</body></html>'
396
+ resp = make_response(html)
397
+ assert resp.emails == ('a@b.com',)
398
+
399
+
400
+ # ── Phone Numbers ───────────────────────────────────────────────────────
401
+
402
+
403
+ class TestPhoneNumbers:
404
+ def test_standard_formats(self):
405
+ html = '<html><body>(800) 123-4567 and 212-555-7890</body></html>'
406
+ resp = make_response(html)
407
+ assert '(800) 123-4567' in resp.phone_numbers
408
+ assert '212-555-7890' in resp.phone_numbers
409
+
410
+ def test_with_country_code(self):
411
+ html = '<html><body>+1 800-123-4567</body></html>'
412
+ resp = make_response(html)
413
+ assert len(resp.phone_numbers) == 1
414
+
415
+ def test_no_phone_numbers(self):
416
+ html = '<html><body>No phones</body></html>'
417
+ resp = make_response(html)
418
+ assert resp.phone_numbers == ()
419
+
420
+
421
+ # ── Links ───────────────────────────────────────────────────────────────
422
+
423
+
424
+ class TestLinks:
425
+ def test_absolute_links(self):
426
+ html = '<html><body><a href="https://other.com/page">link</a></body></html>'
427
+ resp = make_response(html)
428
+ assert 'https://other.com/page' in resp.links
429
+
430
+ def test_relative_links_qualified(self):
431
+ html = '<html><body><a href="/about">about</a></body></html>'
432
+ resp = make_response(html)
433
+ assert 'https://example.com/about' in resp.links
434
+
435
+ def test_no_links(self):
436
+ html = '<html><body><p>No links</p></body></html>'
437
+ resp = make_response(html)
438
+ assert resp.links == ()
439
+
440
+ def test_links_cached(self):
441
+ html = '<html><body><a href="/a">a</a></body></html>'
442
+ resp = make_response(html)
443
+ first = resp.links
444
+ second = resp.links
445
+ assert first is second
446
+
447
+
448
+ # ── Images ──────────────────────────────────────────────────────────────
449
+
450
+
451
+ class TestImages:
452
+ def test_extracts_images(self):
453
+ html = '<html><body><img src="https://example.com/logo.png"></body></html>'
454
+ resp = make_response(html)
455
+ assert 'https://example.com/logo.png' in resp.images
456
+
457
+ def test_relative_images_qualified(self):
458
+ html = '<html><body><img src="/img/logo.png"></body></html>'
459
+ resp = make_response(html)
460
+ assert 'https://example.com/img/logo.png' in resp.images
461
+
462
+ def test_no_images(self):
463
+ html = '<html><body><p>No images</p></body></html>'
464
+ resp = make_response(html)
465
+ assert resp.images == ()
466
+
467
+
468
+ # ── Repr ────────────────────────────────────────────────────────────────
469
+
470
+
471
+ class TestRepr:
472
+ def test_repr(self):
473
+ resp = make_response('<html></html>')
474
+ assert 'Status: 200' in repr(resp)
475
+ assert 'Elapsed Time' in repr(resp)