parsio 0.0.1__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.
- parsio-0.0.1/.gitignore +10 -0
- parsio-0.0.1/.python-version +1 -0
- parsio-0.0.1/LICENSE +21 -0
- parsio-0.0.1/PKG-INFO +25 -0
- parsio-0.0.1/README.md +0 -0
- parsio-0.0.1/parsio/__init__.py +0 -0
- parsio-0.0.1/parsio/agentic/__init__.py +0 -0
- parsio-0.0.1/parsio/client.py +0 -0
- parsio-0.0.1/parsio/core/__init__.py +0 -0
- parsio-0.0.1/parsio/core/browser/__init__.py +23 -0
- parsio-0.0.1/parsio/core/browser/client.py +471 -0
- parsio-0.0.1/parsio/core/browser/decorators.py +74 -0
- parsio-0.0.1/parsio/core/browser/use_cases.py +1131 -0
- parsio-0.0.1/parsio/core/browser/utils.py +81 -0
- parsio-0.0.1/parsio/core/html/__init__.py +0 -0
- parsio-0.0.1/parsio/core/html/content.py +264 -0
- parsio-0.0.1/parsio/core/html/download.py +246 -0
- parsio-0.0.1/parsio/core/html/use_cases.py +567 -0
- parsio-0.0.1/parsio/sdk/__init__.py +0 -0
- parsio-0.0.1/parsio/tools/__init__.py +0 -0
- parsio-0.0.1/pyproject.toml +37 -0
- parsio-0.0.1/uv.lock +999 -0
parsio-0.0.1/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.11
|
parsio-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Okan Yenigün
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
parsio-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parsio
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: All in one web scraping solution
|
|
5
|
+
Project-URL: Homepage, https://github.com/okanyenigun/parsio
|
|
6
|
+
Project-URL: Repository, https://github.com/okanyenigun/parsio
|
|
7
|
+
Author-email: Okan Yenigün <okanyenigun@gmail.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: beautifulsoup,browser,html,selenium,web scraping
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: aiofiles>=25.1.0
|
|
21
|
+
Requires-Dist: aiohttp>=3.13.5
|
|
22
|
+
Requires-Dist: beautifulsoup4>=4.14.3
|
|
23
|
+
Requires-Dist: requests>=2.33.1
|
|
24
|
+
Requires-Dist: selenium>=4.41.0
|
|
25
|
+
Requires-Dist: undetected-chromedriver>=3.5.5
|
parsio-0.0.1/README.md
ADDED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from .use_cases import (
|
|
2
|
+
create_client,
|
|
3
|
+
close_client,
|
|
4
|
+
scrape_page_text,
|
|
5
|
+
scrape_page_html,
|
|
6
|
+
scrape_links_from_page,
|
|
7
|
+
scrape_table_from_page,
|
|
8
|
+
scrape_cards_from_listing_page,
|
|
9
|
+
scrape_infinite_scroll_html,
|
|
10
|
+
scrape_infinite_scroll_attributes,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"create_client",
|
|
15
|
+
"close_client",
|
|
16
|
+
"scrape_page_text",
|
|
17
|
+
"scrape_page_html",
|
|
18
|
+
"scrape_links_from_page",
|
|
19
|
+
"scrape_table_from_page",
|
|
20
|
+
"scrape_cards_from_listing_page",
|
|
21
|
+
"scrape_infinite_scroll_html",
|
|
22
|
+
"scrape_infinite_scroll_attributes",
|
|
23
|
+
]
|
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import undetected_chromedriver as uc
|
|
3
|
+
from selenium.webdriver.common.by import By
|
|
4
|
+
from selenium.webdriver.support.ui import WebDriverWait
|
|
5
|
+
from selenium.webdriver.support import expected_conditions as EC
|
|
6
|
+
from typing import Optional, List, Tuple
|
|
7
|
+
from .decorators import retry_browser
|
|
8
|
+
from .utils import detect_chrome_path_and_version
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SeleniumClient:
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
driver: Optional[uc.Chrome] = None,
|
|
15
|
+
headless: bool = True,
|
|
16
|
+
wait_time: int = 1,
|
|
17
|
+
timeout: int = 30,
|
|
18
|
+
binary_location: Optional[str] = None,
|
|
19
|
+
version_main: Optional[int] = None,
|
|
20
|
+
):
|
|
21
|
+
self._binary_location = binary_location
|
|
22
|
+
self._version_main = version_main
|
|
23
|
+
self._headless = headless
|
|
24
|
+
self._wait_time = wait_time
|
|
25
|
+
self._timeout = timeout
|
|
26
|
+
self._stored_url: Optional[str] = None
|
|
27
|
+
if driver is None:
|
|
28
|
+
self._initialize_driver()
|
|
29
|
+
else:
|
|
30
|
+
self._driver = driver
|
|
31
|
+
|
|
32
|
+
self._by_mapping = {
|
|
33
|
+
"id": By.ID,
|
|
34
|
+
"name": By.NAME,
|
|
35
|
+
"class": By.CLASS_NAME,
|
|
36
|
+
"tag": By.TAG_NAME,
|
|
37
|
+
"link": By.LINK_TEXT,
|
|
38
|
+
"partial_link": By.PARTIAL_LINK_TEXT,
|
|
39
|
+
"css_selector": By.CSS_SELECTOR,
|
|
40
|
+
"xpath": By.XPATH,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def page_source(self) -> str:
|
|
45
|
+
return self._driver.page_source
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def current_url(self) -> str:
|
|
49
|
+
return self._driver.current_url
|
|
50
|
+
|
|
51
|
+
######## Public API ########
|
|
52
|
+
|
|
53
|
+
def close(self) -> None:
|
|
54
|
+
if self._driver:
|
|
55
|
+
try:
|
|
56
|
+
self._driver.quit()
|
|
57
|
+
except Exception as e:
|
|
58
|
+
print(f"[INFO] Error closing driver: {e}")
|
|
59
|
+
# Force kill Chrome processes if quit fails
|
|
60
|
+
try:
|
|
61
|
+
import psutil
|
|
62
|
+
|
|
63
|
+
for proc in psutil.process_iter(["pid", "name", "cmdline"]):
|
|
64
|
+
try:
|
|
65
|
+
cmdline = proc.info.get("cmdline", [])
|
|
66
|
+
if cmdline and any(
|
|
67
|
+
"chrome" in str(arg).lower() for arg in cmdline
|
|
68
|
+
):
|
|
69
|
+
if any(
|
|
70
|
+
"chromedriver" in str(arg).lower()
|
|
71
|
+
or "undetected" in str(arg).lower()
|
|
72
|
+
for arg in cmdline
|
|
73
|
+
):
|
|
74
|
+
proc.kill()
|
|
75
|
+
print(
|
|
76
|
+
f"[INFO] Killed orphaned Chrome process: {proc.info['pid']}"
|
|
77
|
+
)
|
|
78
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
79
|
+
pass
|
|
80
|
+
except ImportError:
|
|
81
|
+
print("[WARN] psutil not available for process cleanup")
|
|
82
|
+
finally:
|
|
83
|
+
self._driver = None
|
|
84
|
+
|
|
85
|
+
def quit(self) -> None:
|
|
86
|
+
self.close()
|
|
87
|
+
|
|
88
|
+
def refresh_page(self) -> None:
|
|
89
|
+
self._driver.refresh()
|
|
90
|
+
time.sleep(self._wait_time)
|
|
91
|
+
|
|
92
|
+
def restart_browser(self) -> None:
|
|
93
|
+
self.close()
|
|
94
|
+
time.sleep(self._wait_time * 2)
|
|
95
|
+
self._initialize_driver()
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
@retry_browser(max_retries=3, enable_progressive=True)
|
|
99
|
+
def go_to(
|
|
100
|
+
self,
|
|
101
|
+
url: str,
|
|
102
|
+
wait_element: Optional[str] = None,
|
|
103
|
+
wait_by: Optional[str] = None,
|
|
104
|
+
) -> None:
|
|
105
|
+
self._ensure_window()
|
|
106
|
+
self._driver.get(url)
|
|
107
|
+
time.sleep(self._wait_time)
|
|
108
|
+
|
|
109
|
+
if wait_element and wait_by:
|
|
110
|
+
locator = self._by_mapping.get(wait_by.lower())
|
|
111
|
+
if not locator:
|
|
112
|
+
raise ValueError(f"Unsupported wait_by value: {wait_by}")
|
|
113
|
+
WebDriverWait(self._driver, self._wait_time * 10).until(
|
|
114
|
+
EC.presence_of_element_located((locator, wait_element))
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
self._driver.implicitly_wait(self._wait_time * 10)
|
|
118
|
+
return
|
|
119
|
+
|
|
120
|
+
def find_element(self, by: str, value: str) -> Optional[object]:
|
|
121
|
+
locator = self._by_mapping.get(by.lower())
|
|
122
|
+
if not locator:
|
|
123
|
+
raise ValueError(f"Unsupported by value: {by}")
|
|
124
|
+
return self._driver.find_element(locator, value)
|
|
125
|
+
|
|
126
|
+
def find_elements(self, by: str, value: str) -> List[object]:
|
|
127
|
+
locator = self._by_mapping.get(by.lower())
|
|
128
|
+
if not locator:
|
|
129
|
+
raise ValueError(f"Unsupported by value: {by}")
|
|
130
|
+
return self._driver.find_elements(locator, value)
|
|
131
|
+
|
|
132
|
+
def scroll_to_bottom(self) -> bool:
|
|
133
|
+
"""
|
|
134
|
+
Scroll the page to the bottom and return whether the viewport actually moved.
|
|
135
|
+
|
|
136
|
+
Returns ``True`` when ``window.scrollY`` changed after the scroll
|
|
137
|
+
(i.e. the page accepted the scroll command), ``False`` when the position
|
|
138
|
+
stayed the same — which usually means an overlay or popup is blocking
|
|
139
|
+
interaction, or the page is not scrollable.
|
|
140
|
+
"""
|
|
141
|
+
prev_y: int = self._driver.execute_script("return window.scrollY;")
|
|
142
|
+
self._driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
|
|
143
|
+
time.sleep(self._wait_time)
|
|
144
|
+
new_y: int = self._driver.execute_script("return window.scrollY;")
|
|
145
|
+
return new_y > prev_y
|
|
146
|
+
|
|
147
|
+
def scroll_to_bottom_slowly(self, step: int = 500, step_delay: float = 0.3) -> bool:
|
|
148
|
+
"""
|
|
149
|
+
Scroll to the bottom in incremental steps so that lazy-loaded content
|
|
150
|
+
has time to appear as each portion of the page enters the viewport.
|
|
151
|
+
|
|
152
|
+
:param step: Pixels to scroll per step.
|
|
153
|
+
:param step_delay: Seconds to pause between each step.
|
|
154
|
+
:returns: ``True`` if the viewport moved at all, ``False`` otherwise.
|
|
155
|
+
"""
|
|
156
|
+
prev_y: int = self._driver.execute_script("return window.scrollY;")
|
|
157
|
+
total_height: int = self._driver.execute_script(
|
|
158
|
+
"return document.body.scrollHeight;"
|
|
159
|
+
)
|
|
160
|
+
current_y: int = prev_y
|
|
161
|
+
|
|
162
|
+
while current_y < total_height:
|
|
163
|
+
current_y = min(current_y + step, total_height)
|
|
164
|
+
self._driver.execute_script(f"window.scrollTo(0, {current_y});")
|
|
165
|
+
time.sleep(step_delay)
|
|
166
|
+
|
|
167
|
+
new_y: int = self._driver.execute_script("return window.scrollY;")
|
|
168
|
+
return new_y > prev_y
|
|
169
|
+
|
|
170
|
+
def click(self, wait_element: str, wait_by: str) -> None:
|
|
171
|
+
locator = self._by_mapping.get(wait_by.lower())
|
|
172
|
+
if not locator:
|
|
173
|
+
raise ValueError(f"Unsupported by value: {wait_by}")
|
|
174
|
+
|
|
175
|
+
element = WebDriverWait(self._driver, self._timeout).until(
|
|
176
|
+
EC.element_to_be_clickable((locator, wait_element))
|
|
177
|
+
)
|
|
178
|
+
element.click()
|
|
179
|
+
time.sleep(self._wait_time)
|
|
180
|
+
return
|
|
181
|
+
|
|
182
|
+
######## Context Manager & Destructor #######
|
|
183
|
+
def __enter__(self):
|
|
184
|
+
"""Context manager entry"""
|
|
185
|
+
return self
|
|
186
|
+
|
|
187
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
188
|
+
"""Context manager exit - ensures cleanup"""
|
|
189
|
+
self.close()
|
|
190
|
+
return False
|
|
191
|
+
|
|
192
|
+
def __del__(self):
|
|
193
|
+
"""Destructor to ensure browser cleanup on object deletion"""
|
|
194
|
+
try:
|
|
195
|
+
self.close()
|
|
196
|
+
except Exception:
|
|
197
|
+
pass
|
|
198
|
+
|
|
199
|
+
######## Internal Methods ########
|
|
200
|
+
|
|
201
|
+
def _initialize_driver(self):
|
|
202
|
+
options = uc.ChromeOptions()
|
|
203
|
+
if self._binary_location:
|
|
204
|
+
options.binary_location = self._binary_location
|
|
205
|
+
|
|
206
|
+
# Set page load strategy to 'eager' to not wait for all resources
|
|
207
|
+
options.page_load_strategy = "eager"
|
|
208
|
+
|
|
209
|
+
# Critical stability options
|
|
210
|
+
options.add_argument("--no-sandbox")
|
|
211
|
+
options.add_argument("--disable-dev-shm-usage")
|
|
212
|
+
options.add_argument("--disable-gpu")
|
|
213
|
+
options.add_argument("--window-size=1920,1080")
|
|
214
|
+
options.add_argument("--disable-infobars")
|
|
215
|
+
options.add_argument("--disable-notifications")
|
|
216
|
+
options.add_argument("--disable-popup-blocking")
|
|
217
|
+
|
|
218
|
+
# Additional stability options to prevent crashes
|
|
219
|
+
options.add_argument("--disable-blink-features=AutomationControlled")
|
|
220
|
+
options.add_argument("--disable-extensions")
|
|
221
|
+
options.add_argument("--no-first-run")
|
|
222
|
+
options.add_argument("--no-default-browser-check")
|
|
223
|
+
options.add_argument("--disable-background-networking")
|
|
224
|
+
options.add_argument("--disable-background-timer-throttling")
|
|
225
|
+
options.add_argument("--disable-backgrounding-occluded-windows")
|
|
226
|
+
options.add_argument("--disable-breakpad")
|
|
227
|
+
options.add_argument("--disable-component-extensions-with-background-pages")
|
|
228
|
+
options.add_argument("--disable-features=TranslateUI,BlinkGenPropertyTrees")
|
|
229
|
+
options.add_argument("--disable-ipc-flooding-protection")
|
|
230
|
+
options.add_argument("--disable-renderer-backgrounding")
|
|
231
|
+
options.add_argument("--force-color-profile=srgb")
|
|
232
|
+
options.add_argument("--metrics-recording-only")
|
|
233
|
+
options.add_argument("--mute-audio")
|
|
234
|
+
|
|
235
|
+
# Renderer timeout prevention
|
|
236
|
+
options.add_argument("--disable-hang-monitor")
|
|
237
|
+
options.add_argument("--disable-prompt-on-repost")
|
|
238
|
+
options.add_argument("--disable-sync")
|
|
239
|
+
|
|
240
|
+
# Let Chrome pick a free remote-debugging port; required for Canary stability
|
|
241
|
+
options.add_argument("--remote-debugging-port=0")
|
|
242
|
+
|
|
243
|
+
# Auto-detect Chrome/Canary if not provided
|
|
244
|
+
if not self._binary_location or not self._version_main:
|
|
245
|
+
detected_path, detected_version = detect_chrome_path_and_version()
|
|
246
|
+
if not self._binary_location:
|
|
247
|
+
self._binary_location = detected_path
|
|
248
|
+
options.binary_location = self._binary_location
|
|
249
|
+
if not self._version_main:
|
|
250
|
+
self._version_main = detected_version
|
|
251
|
+
|
|
252
|
+
self._driver = uc.Chrome(
|
|
253
|
+
options=options,
|
|
254
|
+
version_main=self._version_main,
|
|
255
|
+
headless=self._headless,
|
|
256
|
+
browser_executable_path=self._binary_location,
|
|
257
|
+
use_subprocess=True, # Keeps chromedriver process independent; more stable with Canary
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
# Give Chrome more time to stabilize
|
|
261
|
+
time.sleep(self._wait_time * 3)
|
|
262
|
+
|
|
263
|
+
# Set longer timeouts to prevent hanging
|
|
264
|
+
self._driver.set_page_load_timeout(60) # Increased from 30 to 60
|
|
265
|
+
self._driver.set_script_timeout(60) # Add script timeout
|
|
266
|
+
|
|
267
|
+
# Maximize window for better stability
|
|
268
|
+
try:
|
|
269
|
+
self._driver.maximize_window()
|
|
270
|
+
except Exception:
|
|
271
|
+
pass
|
|
272
|
+
|
|
273
|
+
def wait_for_element(
|
|
274
|
+
self, locator: Tuple[str, str], timeout: Optional[int] = None
|
|
275
|
+
) -> None:
|
|
276
|
+
wait_timeout = timeout or self._timeout
|
|
277
|
+
WebDriverWait(self._driver, wait_timeout).until(
|
|
278
|
+
EC.presence_of_element_located(locator)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
def find_elements_by_locator(self, locator: Tuple[str, str]) -> List:
|
|
282
|
+
"""Find all elements matching a raw Selenium ``(By, value)`` locator tuple."""
|
|
283
|
+
return self._driver.find_elements(*locator)
|
|
284
|
+
|
|
285
|
+
def find_element_by_locator(self, locator: Tuple[str, str]):
|
|
286
|
+
"""Find a single element matching a raw Selenium ``(By, value)`` locator tuple.
|
|
287
|
+
Raises ``NoSuchElementException`` when no match is found."""
|
|
288
|
+
return self._driver.find_element(*locator)
|
|
289
|
+
|
|
290
|
+
def execute_script(self, script: str, *args):
|
|
291
|
+
"""Execute arbitrary JavaScript in the current browser context."""
|
|
292
|
+
return self._driver.execute_script(script, *args)
|
|
293
|
+
|
|
294
|
+
def dismiss_overlays(self) -> bool:
|
|
295
|
+
"""
|
|
296
|
+
Attempt to automatically detect and dismiss a visible popup or overlay.
|
|
297
|
+
|
|
298
|
+
Uses JavaScript to scan the DOM for the most likely dismiss button using
|
|
299
|
+
three passes in priority order:
|
|
300
|
+
|
|
301
|
+
1. **Known consent-platform selectors** — OneTrust, Cookiebot, Cookie
|
|
302
|
+
Consent, and similar SDKs have predictable element IDs/classes.
|
|
303
|
+
2. **Dialog roles** — Any ``role="dialog"`` or ``role="alertdialog"``
|
|
304
|
+
container that is visible on screen; inside it, the first button
|
|
305
|
+
whose text contains a common dismiss keyword (accept, agree, close,
|
|
306
|
+
OK, etc.) is clicked.
|
|
307
|
+
3. **Full-page button scan** — All ``<button>`` and ``[role="button"]``
|
|
308
|
+
elements are checked for exact-match dismiss phrases such as
|
|
309
|
+
``"accept all"`` or ``"kabul et"`` (Turkish).
|
|
310
|
+
|
|
311
|
+
Returns ``True`` when a button was found and clicked, ``False`` when
|
|
312
|
+
nothing matched (page has no detectable overlay).
|
|
313
|
+
"""
|
|
314
|
+
_JS = """
|
|
315
|
+
// --- Pass 1: known consent-platform element selectors ---
|
|
316
|
+
var knownSelectors = [
|
|
317
|
+
'#onetrust-accept-btn-handler',
|
|
318
|
+
'#accept-recommended-btn-handler',
|
|
319
|
+
'.onetrust-accept-btn-handler',
|
|
320
|
+
'#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll',
|
|
321
|
+
'#CybotCookiebotDialogBodyButtonAccept',
|
|
322
|
+
'[data-cookiebanner="accept_button"]',
|
|
323
|
+
'.cc-btn.cc-allow',
|
|
324
|
+
'.cc-accept-all',
|
|
325
|
+
'[aria-label="Accept cookies"]',
|
|
326
|
+
'[aria-label="Accept all cookies"]',
|
|
327
|
+
'[data-testid="cookie-accept"]',
|
|
328
|
+
'[data-testid="accept-all-cookies"]',
|
|
329
|
+
'button[id*="accept"][id*="cookie"]',
|
|
330
|
+
'button[class*="accept"][class*="cookie"]',
|
|
331
|
+
'button[id*="consent"][id*="accept"]',
|
|
332
|
+
];
|
|
333
|
+
for (var i = 0; i < knownSelectors.length; i++) {
|
|
334
|
+
try {
|
|
335
|
+
var el = document.querySelector(knownSelectors[i]);
|
|
336
|
+
if (el && el.offsetParent !== null && el.getBoundingClientRect().width > 0) {
|
|
337
|
+
return el;
|
|
338
|
+
}
|
|
339
|
+
} catch(e) {}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// --- Pass 2: visible dialog containers with dismiss-like button text ---
|
|
343
|
+
var dismissKeywords = ['accept', 'agree', 'allow', 'ok', 'close', 'got it',
|
|
344
|
+
'continue', 'confirm', 'acknowledge',
|
|
345
|
+
'kabul', 'tamam', 'kapat', 'anladim', 'anladım'];
|
|
346
|
+
var dialogs = document.querySelectorAll(
|
|
347
|
+
'[role="dialog"], [role="alertdialog"], '
|
|
348
|
+
+ '[class*="cookie"], [class*="consent"], [class*="gdpr"], '
|
|
349
|
+
+ '[class*="modal"], [class*="overlay"], [class*="popup"], '
|
|
350
|
+
+ '[id*="cookie"], [id*="consent"], [id*="gdpr"]'
|
|
351
|
+
);
|
|
352
|
+
for (var d = 0; d < dialogs.length; d++) {
|
|
353
|
+
var container = dialogs[d];
|
|
354
|
+
if (container.offsetParent === null) continue;
|
|
355
|
+
var rect = container.getBoundingClientRect();
|
|
356
|
+
if (rect.width === 0 || rect.height === 0) continue;
|
|
357
|
+
var btns = container.querySelectorAll(
|
|
358
|
+
'button, a[role="button"], [type="button"], [type="submit"]'
|
|
359
|
+
);
|
|
360
|
+
for (var b = 0; b < btns.length; b++) {
|
|
361
|
+
var btn = btns[b];
|
|
362
|
+
if (btn.offsetParent === null) continue;
|
|
363
|
+
var txt = (btn.innerText || btn.textContent || '').trim().toLowerCase();
|
|
364
|
+
for (var k = 0; k < dismissKeywords.length; k++) {
|
|
365
|
+
if (txt.indexOf(dismissKeywords[k]) !== -1) return btn;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// --- Pass 3: full-page scan for exact dismiss phrases ---
|
|
371
|
+
var exactPhrases = [
|
|
372
|
+
'accept all', 'accept all cookies', 'allow all', 'allow all cookies',
|
|
373
|
+
'i agree', 'agree to all', 'i accept', 'accept & close',
|
|
374
|
+
'kabul et', 'tümünü kabul et', 'hepsini kabul et'
|
|
375
|
+
];
|
|
376
|
+
var allBtns = document.querySelectorAll('button, [role="button"]');
|
|
377
|
+
for (var i = 0; i < allBtns.length; i++) {
|
|
378
|
+
var btn = allBtns[i];
|
|
379
|
+
if (btn.offsetParent === null) continue;
|
|
380
|
+
var r = btn.getBoundingClientRect();
|
|
381
|
+
if (r.width === 0 || r.height === 0) continue;
|
|
382
|
+
var txt = (btn.innerText || btn.textContent || '').trim().toLowerCase();
|
|
383
|
+
for (var p = 0; p < exactPhrases.length; p++) {
|
|
384
|
+
if (txt === exactPhrases[p] || txt.indexOf(exactPhrases[p]) !== -1) {
|
|
385
|
+
return btn;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
return null;
|
|
391
|
+
"""
|
|
392
|
+
try:
|
|
393
|
+
el = self._driver.execute_script(_JS)
|
|
394
|
+
if el is not None:
|
|
395
|
+
el.click()
|
|
396
|
+
time.sleep(0.8)
|
|
397
|
+
return True
|
|
398
|
+
except Exception:
|
|
399
|
+
pass
|
|
400
|
+
return False
|
|
401
|
+
|
|
402
|
+
def save_screenshot(self, path: str) -> None:
|
|
403
|
+
"""Save a PNG screenshot of the current viewport to *path*."""
|
|
404
|
+
self._driver.save_screenshot(path)
|
|
405
|
+
|
|
406
|
+
def get_window_size(self) -> dict:
|
|
407
|
+
"""Return the current window size as ``{"width": int, "height": int}``."""
|
|
408
|
+
return self._driver.get_window_size()
|
|
409
|
+
|
|
410
|
+
def set_window_size(self, width: int, height: int) -> None:
|
|
411
|
+
"""Resize the browser window."""
|
|
412
|
+
self._driver.set_window_size(width, height)
|
|
413
|
+
|
|
414
|
+
def _ensure_window(self) -> None:
|
|
415
|
+
"""Recover from a closed window (common with Chrome Canary nightly builds).
|
|
416
|
+
|
|
417
|
+
1. If at least one handle exists, switch to the last one and return.
|
|
418
|
+
2. Otherwise, use CDP to open a fresh blank target and switch to it.
|
|
419
|
+
"""
|
|
420
|
+
try:
|
|
421
|
+
handles = self._driver.window_handles
|
|
422
|
+
if handles:
|
|
423
|
+
self._driver.switch_to.window(handles[-1])
|
|
424
|
+
return
|
|
425
|
+
except Exception:
|
|
426
|
+
pass
|
|
427
|
+
|
|
428
|
+
# No open windows — create one via CDP
|
|
429
|
+
try:
|
|
430
|
+
self._driver.execute_cdp_cmd("Target.createTarget", {"url": ""})
|
|
431
|
+
time.sleep(1.0)
|
|
432
|
+
handles = self._driver.window_handles
|
|
433
|
+
if handles:
|
|
434
|
+
self._driver.switch_to.window(handles[-1])
|
|
435
|
+
except Exception:
|
|
436
|
+
pass # Will surface as the original error on the next line
|
|
437
|
+
|
|
438
|
+
def _store_current_url(self) -> None:
|
|
439
|
+
try:
|
|
440
|
+
self._stored_url = self._driver.current_url
|
|
441
|
+
except Exception:
|
|
442
|
+
pass
|
|
443
|
+
|
|
444
|
+
def _get_stored_url(self) -> Optional[str]:
|
|
445
|
+
return self._stored_url
|
|
446
|
+
|
|
447
|
+
def _refresh_and_restore(self) -> None:
|
|
448
|
+
self._driver.refresh()
|
|
449
|
+
time.sleep(self._wait_time * 2)
|
|
450
|
+
|
|
451
|
+
def _reset_and_restore(self, url: Optional[str]) -> None:
|
|
452
|
+
self.close()
|
|
453
|
+
time.sleep(self._wait_time * 2)
|
|
454
|
+
self._initialize_driver()
|
|
455
|
+
if url:
|
|
456
|
+
self._driver.get(url)
|
|
457
|
+
time.sleep(self._wait_time)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def resolve_client(
|
|
461
|
+
driver: Optional[SeleniumClient],
|
|
462
|
+
headless: bool,
|
|
463
|
+
timeout: int,
|
|
464
|
+
) -> Tuple[SeleniumClient, bool]:
|
|
465
|
+
"""
|
|
466
|
+
Return ``(client, owned)`` where *owned* is True when this call created the
|
|
467
|
+
client and therefore is responsible for closing it.
|
|
468
|
+
"""
|
|
469
|
+
if driver is not None:
|
|
470
|
+
return driver, False
|
|
471
|
+
return SeleniumClient(headless=headless, timeout=timeout), True
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from functools import wraps
|
|
3
|
+
from typing import Callable, Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def retry_browser(max_retries: int = 3, enable_progressive: bool = True):
|
|
7
|
+
"""
|
|
8
|
+
Decorator that retries a method with progressive fallback strategies.
|
|
9
|
+
|
|
10
|
+
Strategy:
|
|
11
|
+
1. Normal retries
|
|
12
|
+
2. After retries fail: refresh page and retry
|
|
13
|
+
3. If still failing: reset driver and retry
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
max_retries: Maximum number of retry attempts per strategy
|
|
17
|
+
enable_progressive: Enable progressive fallback (refresh -> reset)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def decorator(func: Callable) -> Callable:
|
|
21
|
+
@wraps(func)
|
|
22
|
+
def wrapper(self, *args, **kwargs) -> Any:
|
|
23
|
+
last_exception = None
|
|
24
|
+
|
|
25
|
+
# Phase 1: Normal retries
|
|
26
|
+
for attempt in range(max_retries):
|
|
27
|
+
try:
|
|
28
|
+
return func(self, *args, **kwargs)
|
|
29
|
+
except Exception as e:
|
|
30
|
+
print(f"[WARN] Attempt {attempt + 1} failed: {e}")
|
|
31
|
+
last_exception = e
|
|
32
|
+
if attempt < max_retries - 1:
|
|
33
|
+
time.sleep(self._wait_time * (attempt + 1))
|
|
34
|
+
|
|
35
|
+
if not enable_progressive:
|
|
36
|
+
raise last_exception
|
|
37
|
+
|
|
38
|
+
# Phase 2: Refresh page and retry
|
|
39
|
+
try:
|
|
40
|
+
self._store_current_url()
|
|
41
|
+
self._refresh_and_restore()
|
|
42
|
+
|
|
43
|
+
for attempt in range(max_retries):
|
|
44
|
+
try:
|
|
45
|
+
return func(self, *args, **kwargs)
|
|
46
|
+
except Exception as e:
|
|
47
|
+
print(f"[WARN] Attempt {attempt + 1} after refresh failed: {e}")
|
|
48
|
+
last_exception = e
|
|
49
|
+
if attempt < max_retries - 1:
|
|
50
|
+
time.sleep(self._wait_time * (attempt + 1))
|
|
51
|
+
except Exception:
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
# Phase 3: Reset driver and retry
|
|
55
|
+
try:
|
|
56
|
+
stored_url = self._get_stored_url()
|
|
57
|
+
self._reset_and_restore(stored_url)
|
|
58
|
+
|
|
59
|
+
for attempt in range(max_retries):
|
|
60
|
+
try:
|
|
61
|
+
return func(self, *args, **kwargs)
|
|
62
|
+
except Exception as e:
|
|
63
|
+
print(f"[WARN] Attempt {attempt + 1} after reset failed: {e}")
|
|
64
|
+
last_exception = e
|
|
65
|
+
if attempt < max_retries - 1:
|
|
66
|
+
time.sleep(self._wait_time * (attempt + 1))
|
|
67
|
+
except Exception:
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
raise last_exception
|
|
71
|
+
|
|
72
|
+
return wrapper
|
|
73
|
+
|
|
74
|
+
return decorator
|