cian-playwright 2.0.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 (35) hide show
  1. cian_playwright-2.0.0/LICENSE +21 -0
  2. cian_playwright-2.0.0/PKG-INFO +103 -0
  3. cian_playwright-2.0.0/README.md +75 -0
  4. cian_playwright-2.0.0/pyproject.toml +47 -0
  5. cian_playwright-2.0.0/setup.cfg +4 -0
  6. cian_playwright-2.0.0/src/cian_parser/__init__.py +15 -0
  7. cian_playwright-2.0.0/src/cian_parser/base_list.py +217 -0
  8. cian_playwright-2.0.0/src/cian_parser/browser.py +94 -0
  9. cian_playwright-2.0.0/src/cian_parser/constants.py +904 -0
  10. cian_playwright-2.0.0/src/cian_parser/csv_saver.py +24 -0
  11. cian_playwright-2.0.0/src/cian_parser/exceptions.py +23 -0
  12. cian_playwright-2.0.0/src/cian_parser/flat/__init__.py +0 -0
  13. cian_playwright-2.0.0/src/cian_parser/flat/list_parser.py +44 -0
  14. cian_playwright-2.0.0/src/cian_parser/flat/page_parser.py +96 -0
  15. cian_playwright-2.0.0/src/cian_parser/helpers.py +280 -0
  16. cian_playwright-2.0.0/src/cian_parser/newobject/__init__.py +0 -0
  17. cian_playwright-2.0.0/src/cian_parser/newobject/list_parser.py +155 -0
  18. cian_playwright-2.0.0/src/cian_parser/newobject/page_parser.py +89 -0
  19. cian_playwright-2.0.0/src/cian_parser/parser.py +258 -0
  20. cian_playwright-2.0.0/src/cian_parser/suburban/__init__.py +0 -0
  21. cian_playwright-2.0.0/src/cian_parser/suburban/list_parser.py +44 -0
  22. cian_playwright-2.0.0/src/cian_parser/suburban/page_parser.py +91 -0
  23. cian_playwright-2.0.0/src/cian_parser/url_builder.py +155 -0
  24. cian_playwright-2.0.0/src/cian_playwright.egg-info/PKG-INFO +103 -0
  25. cian_playwright-2.0.0/src/cian_playwright.egg-info/SOURCES.txt +33 -0
  26. cian_playwright-2.0.0/src/cian_playwright.egg-info/dependency_links.txt +1 -0
  27. cian_playwright-2.0.0/src/cian_playwright.egg-info/requires.txt +5 -0
  28. cian_playwright-2.0.0/src/cian_playwright.egg-info/top_level.txt +1 -0
  29. cian_playwright-2.0.0/tests/test_constants.py +31 -0
  30. cian_playwright-2.0.0/tests/test_e2e.py +729 -0
  31. cian_playwright-2.0.0/tests/test_e2e_isolated.py +69 -0
  32. cian_playwright-2.0.0/tests/test_exceptions.py +25 -0
  33. cian_playwright-2.0.0/tests/test_helpers.py +86 -0
  34. cian_playwright-2.0.0/tests/test_url_builder.py +136 -0
  35. cian_playwright-2.0.0/tests/test_validators.py +64 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mikhail
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.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: cian-playwright
3
+ Version: 2.0.0
4
+ Summary: Parser for Cian.ru real estate listings (Playwright-based)
5
+ Author-email: Mikhail <tarminik@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/tarminik/cian-parser
8
+ Project-URL: Repository, https://github.com/tarminik/cian-parser
9
+ Project-URL: Issues, https://github.com/tarminik/cian-parser/issues
10
+ Keywords: cian,parser,real-estate,scraper,playwright
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: playwright>=1.40
24
+ Requires-Dist: playwright-stealth>=2.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # cian-parser
30
+
31
+ Playwright-based parser for [Cian.ru](https://cian.ru) real estate listings.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install cian-parser
37
+ playwright install chromium
38
+ ```
39
+
40
+ ## Quick start
41
+
42
+ ```python
43
+ from cian_parser import CianParser
44
+
45
+ with CianParser("Москва") as parser:
46
+ # Sale
47
+ flats = parser.get_flats(deal_type="sale", rooms=(1, 2))
48
+
49
+ # Long-term rent
50
+ rent = parser.get_flats(deal_type="rent_long", rooms="all")
51
+
52
+ # Short-term rent
53
+ daily = parser.get_flats(deal_type="rent_short")
54
+
55
+ # Suburban
56
+ houses = parser.get_suburban("house", deal_type="sale")
57
+
58
+ # New construction
59
+ newbuilds = parser.get_newobjects()
60
+ ```
61
+
62
+ ## API
63
+
64
+ ### `CianParser(location, proxies=None)`
65
+
66
+ - **location** — city name (e.g. `"Москва"`). See `cian_parser.list_locations()` for all options.
67
+ - **proxies** — optional proxy URL string for Playwright.
68
+
69
+ ### `get_flats(deal_type, rooms="all", with_saving_csv=False, with_extra_data=False, additional_settings=None)`
70
+
71
+ | Parameter | Type | Description |
72
+ |-----------|------|-------------|
73
+ | `deal_type` | `str` | `"sale"`, `"rent_long"`, or `"rent_short"` |
74
+ | `rooms` | `int \| str \| tuple` | `1`–`5`, `"studio"`, `"all"`, or tuple like `(1, 2, "studio")` |
75
+ | `with_saving_csv` | `bool` | Save results to CSV |
76
+ | `with_extra_data` | `bool` | Parse detail pages for extra fields (slower) |
77
+ | `additional_settings` | `dict` | Filters: `min_price`, `max_price`, `metro`, `district`, `sort_by`, etc. |
78
+
79
+ ### `get_suburban(suburban_type, deal_type, ...)`
80
+
81
+ Same parameters as `get_flats`, plus:
82
+
83
+ | Parameter | Type | Description |
84
+ |-----------|------|-------------|
85
+ | `suburban_type` | `str` | `"house"`, `"house-part"`, `"land-plot"`, or `"townhouse"` |
86
+
87
+ ### `get_newobjects(with_saving_csv=False)`
88
+
89
+ Parse new construction listings.
90
+
91
+ ### Helpers
92
+
93
+ ```python
94
+ from cian_parser import list_locations, list_metro_stations, list_districts
95
+
96
+ list_locations() # [("Москва", "1"), ("Санкт-Петербург", "2"), ...]
97
+ list_metro_stations() # {"Москва": [("Арбатская", "1"), ...], ...}
98
+ list_districts("Москва") # [("Арбат", "13"), ...]
99
+ ```
100
+
101
+ ## License
102
+
103
+ [MIT](LICENSE)
@@ -0,0 +1,75 @@
1
+ # cian-parser
2
+
3
+ Playwright-based parser for [Cian.ru](https://cian.ru) real estate listings.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install cian-parser
9
+ playwright install chromium
10
+ ```
11
+
12
+ ## Quick start
13
+
14
+ ```python
15
+ from cian_parser import CianParser
16
+
17
+ with CianParser("Москва") as parser:
18
+ # Sale
19
+ flats = parser.get_flats(deal_type="sale", rooms=(1, 2))
20
+
21
+ # Long-term rent
22
+ rent = parser.get_flats(deal_type="rent_long", rooms="all")
23
+
24
+ # Short-term rent
25
+ daily = parser.get_flats(deal_type="rent_short")
26
+
27
+ # Suburban
28
+ houses = parser.get_suburban("house", deal_type="sale")
29
+
30
+ # New construction
31
+ newbuilds = parser.get_newobjects()
32
+ ```
33
+
34
+ ## API
35
+
36
+ ### `CianParser(location, proxies=None)`
37
+
38
+ - **location** — city name (e.g. `"Москва"`). See `cian_parser.list_locations()` for all options.
39
+ - **proxies** — optional proxy URL string for Playwright.
40
+
41
+ ### `get_flats(deal_type, rooms="all", with_saving_csv=False, with_extra_data=False, additional_settings=None)`
42
+
43
+ | Parameter | Type | Description |
44
+ |-----------|------|-------------|
45
+ | `deal_type` | `str` | `"sale"`, `"rent_long"`, or `"rent_short"` |
46
+ | `rooms` | `int \| str \| tuple` | `1`–`5`, `"studio"`, `"all"`, or tuple like `(1, 2, "studio")` |
47
+ | `with_saving_csv` | `bool` | Save results to CSV |
48
+ | `with_extra_data` | `bool` | Parse detail pages for extra fields (slower) |
49
+ | `additional_settings` | `dict` | Filters: `min_price`, `max_price`, `metro`, `district`, `sort_by`, etc. |
50
+
51
+ ### `get_suburban(suburban_type, deal_type, ...)`
52
+
53
+ Same parameters as `get_flats`, plus:
54
+
55
+ | Parameter | Type | Description |
56
+ |-----------|------|-------------|
57
+ | `suburban_type` | `str` | `"house"`, `"house-part"`, `"land-plot"`, or `"townhouse"` |
58
+
59
+ ### `get_newobjects(with_saving_csv=False)`
60
+
61
+ Parse new construction listings.
62
+
63
+ ### Helpers
64
+
65
+ ```python
66
+ from cian_parser import list_locations, list_metro_stations, list_districts
67
+
68
+ list_locations() # [("Москва", "1"), ("Санкт-Петербург", "2"), ...]
69
+ list_metro_stations() # {"Москва": [("Арбатская", "1"), ...], ...}
70
+ list_districts("Москва") # [("Арбат", "13"), ...]
71
+ ```
72
+
73
+ ## License
74
+
75
+ [MIT](LICENSE)
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cian-playwright"
7
+ version = "2.0.0"
8
+ description = "Parser for Cian.ru real estate listings (Playwright-based)"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [
13
+ { name = "Mikhail", email = "tarminik@gmail.com" },
14
+ ]
15
+ keywords = ["cian", "parser", "real-estate", "scraper", "playwright"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Internet :: WWW/HTTP :: Indexing/Search",
26
+ ]
27
+ dependencies = [
28
+ "playwright>=1.40",
29
+ "playwright-stealth>=2.0",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ dev = ["pytest"]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/tarminik/cian-parser"
37
+ Repository = "https://github.com/tarminik/cian-parser"
38
+ Issues = "https://github.com/tarminik/cian-parser/issues"
39
+
40
+ [tool.pytest.ini_options]
41
+ markers = [
42
+ "live: end-to-end tests that hit real Cian.ru (require network + chromium)",
43
+ "slow: slow tests (newobject, extra_data with detail pages)",
44
+ ]
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,15 @@
1
+ """cian_parser — Playwright-based parser for Cian.ru real estate listings."""
2
+
3
+ from cian_parser.parser import CianParser, list_locations, list_metro_stations, list_districts
4
+ from cian_parser.exceptions import CianParserError, CaptchaError, LocationNotFoundError, BrowserNotInstalledError
5
+
6
+ __all__ = [
7
+ "CianParser",
8
+ "list_locations",
9
+ "list_metro_stations",
10
+ "list_districts",
11
+ "CianParserError",
12
+ "CaptchaError",
13
+ "LocationNotFoundError",
14
+ "BrowserNotInstalledError",
15
+ ]
@@ -0,0 +1,217 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import random
5
+ import time
6
+ from typing import Any
7
+
8
+ from playwright.sync_api import Page
9
+
10
+ from cian_parser.browser import BrowserManager
11
+ from cian_parser.csv_saver import save_to_csv
12
+ from cian_parser.constants import SPECIFIC_FIELDS_FOR_RENT_LONG, SPECIFIC_FIELDS_FOR_RENT_SHORT, SPECIFIC_FIELDS_FOR_SALE
13
+ from cian_parser.exceptions import CaptchaError
14
+ from cian_parser.helpers import define_deal_url_id
15
+
16
+ logger = logging.getLogger("cian_parser")
17
+
18
+
19
+ class BaseListParser:
20
+ def __init__(
21
+ self,
22
+ browser: BrowserManager,
23
+ accommodation_type: str,
24
+ deal_type: str,
25
+ rent_period_type: int | None,
26
+ location_name: str,
27
+ with_saving_csv: bool = False,
28
+ with_extra_data: bool = False,
29
+ additional_settings: dict[str, Any] | None = None,
30
+ object_type: str | None = None,
31
+ ):
32
+ self.browser = browser
33
+ self.accommodation_type = accommodation_type
34
+ self.deal_type = deal_type
35
+ self.rent_period_type = rent_period_type
36
+ self.location_name = location_name
37
+ self.with_saving_csv = with_saving_csv
38
+ self.with_extra_data = with_extra_data
39
+ self.additional_settings = additional_settings
40
+ self.object_type = object_type
41
+
42
+ self.result: list[dict[str, Any]] = []
43
+ self.result_set: set[str] = set()
44
+ self.count_parsed_offers = 0
45
+ self.start_page = 1 if (additional_settings is None or "start_page" not in additional_settings) else additional_settings["start_page"]
46
+ self.end_page = 100 if (additional_settings is None or "end_page" not in additional_settings) else additional_settings["end_page"]
47
+ self.file_path = self.build_file_path()
48
+
49
+ def is_sale(self) -> bool:
50
+ return self.deal_type == "sale"
51
+
52
+ def is_rent_long(self) -> bool:
53
+ return self.deal_type == "rent" and self.rent_period_type == 4
54
+
55
+ def is_rent_short(self) -> bool:
56
+ return self.deal_type == "rent" and self.rent_period_type == 2
57
+
58
+ def build_file_path(self) -> str:
59
+ raise NotImplementedError
60
+
61
+ def parse_card(self, card: Any) -> dict[str, Any]:
62
+ raise NotImplementedError
63
+
64
+ def parse_detail_page(self, url: str) -> dict[str, Any]:
65
+ raise NotImplementedError
66
+
67
+ def remove_unnecessary_fields(self, record: dict[str, Any]) -> dict[str, Any]:
68
+ if self.is_sale():
69
+ for field in SPECIFIC_FIELDS_FOR_RENT_LONG | SPECIFIC_FIELDS_FOR_RENT_SHORT:
70
+ record.pop(field, None)
71
+ elif self.is_rent_long():
72
+ for field in SPECIFIC_FIELDS_FOR_RENT_SHORT | SPECIFIC_FIELDS_FOR_SALE:
73
+ record.pop(field, None)
74
+ elif self.is_rent_short():
75
+ for field in SPECIFIC_FIELDS_FOR_RENT_LONG | SPECIFIC_FIELDS_FOR_SALE:
76
+ record.pop(field, None)
77
+ return record
78
+
79
+ def run(self, url_format: str) -> list[dict[str, Any]]:
80
+ """Run pagination loop. Returns collected results."""
81
+ page = self.browser.new_page()
82
+
83
+ try:
84
+ self._paginate(page, url_format)
85
+ finally:
86
+ page.close()
87
+
88
+ return self.result
89
+
90
+ def _paginate(self, page: Page, url_format: str) -> None:
91
+ logger.info("Starting collection from page %d to %d", self.start_page, self.end_page)
92
+
93
+ if self.with_saving_csv:
94
+ logger.info("CSV will be saved to: %s", self.file_path)
95
+
96
+ page_number = self.start_page - 1
97
+
98
+ while page_number < self.end_page:
99
+ page_number += 1
100
+ attempt = 0
101
+ page_parsed = False
102
+
103
+ while attempt < 3 and not page_parsed:
104
+ try:
105
+ page_parsed, should_stop = self._parse_page(page, url_format, page_number, attempt)
106
+ if should_stop:
107
+ return
108
+ except CaptchaError:
109
+ raise
110
+ except Exception as exc:
111
+ attempt += 1
112
+ delay = attempt * 5
113
+ logger.warning("Error on page %d (attempt %d/3): %s. Retrying in %ds...", page_number, attempt, exc, delay)
114
+ if attempt >= 3:
115
+ logger.error("Failed to parse page %d after 3 attempts: %s", page_number, exc)
116
+ return
117
+ time.sleep(delay)
118
+
119
+ logger.info("Collection complete. Total parsed: %d", self.count_parsed_offers)
120
+
121
+ def _parse_page(self, page: Page, url_format: str, page_number: int, attempt: int) -> tuple[bool, bool]:
122
+ """Parse a single list page. Returns (page_parsed, should_stop)."""
123
+ url = url_format.format(page_number)
124
+
125
+ if page_number == self.start_page and attempt == 0:
126
+ logger.info("Starting URL: %s", url)
127
+
128
+ self.browser.navigate(page, url)
129
+ page.wait_for_timeout(random.randint(3000, 5000))
130
+
131
+ # Scroll to load lazy content
132
+ page.evaluate("window.scrollTo(0, document.body.scrollHeight / 2)")
133
+ page.wait_for_timeout(1000)
134
+ page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
135
+ page.wait_for_timeout(1000)
136
+
137
+ # Check for CAPTCHA
138
+ page_text = page.inner_text("body")
139
+ if "Captcha" in page_text or "captcha" in page_text:
140
+ logger.warning("CAPTCHA detected on page %d", page_number)
141
+ raise CaptchaError(
142
+ f"CAPTCHA detected on page {page_number}. Collected {len(self.result)} results before CAPTCHA.",
143
+ partial_results=list(self.result),
144
+ )
145
+
146
+ cards = self._get_cards(page)
147
+ if not cards:
148
+ logger.info("No cards found on page %d, stopping.", page_number)
149
+ return True, True
150
+
151
+ logger.info("Page %d: %d cards found", page_number, len(cards))
152
+
153
+ for card in cards:
154
+ self._process_card(card)
155
+
156
+ logger.info("Total parsed so far: %d", self.count_parsed_offers)
157
+
158
+ # Check pagination
159
+ has_next = self._has_next_page(page, page_number)
160
+ if not has_next:
161
+ logger.info("Last page reached (%d).", page_number)
162
+ return True, True
163
+
164
+ time.sleep(random.uniform(2, 4))
165
+ return True, False
166
+
167
+ def _get_cards(self, page: Page) -> list:
168
+ return page.query_selector_all("article[data-name='CardComponent']")
169
+
170
+ def _has_next_page(self, page: Page, current_page: int) -> bool:
171
+ next_btn = page.query_selector("[data-name='Pagination'] [class*='--next--']")
172
+ if next_btn:
173
+ return True
174
+
175
+ pag = page.query_selector("[data-name='Pagination']")
176
+ if not pag:
177
+ return False
178
+
179
+ page_links = page.query_selector_all("[data-name='Pagination'] li")
180
+ last_page = current_page
181
+ for pl in page_links:
182
+ txt = pl.inner_text().strip()
183
+ if txt.isdigit():
184
+ last_page = max(last_page, int(txt))
185
+
186
+ return current_page < last_page
187
+
188
+ def _process_card(self, card: Any) -> None:
189
+ card_data = self.parse_card(card)
190
+ url = card_data.get("url", "")
191
+
192
+ if not url:
193
+ return
194
+
195
+ url_id = define_deal_url_id(url)
196
+ if url_id in self.result_set:
197
+ return
198
+
199
+ page_data: dict[str, Any] = {}
200
+ if self.with_extra_data:
201
+ page_data = self.parse_detail_page(url)
202
+ time.sleep(4)
203
+
204
+ self.result_set.add(url_id)
205
+ # Merge detail data without overwriting valid card-level values with sentinels
206
+ for key, value in page_data.items():
207
+ if key in card_data and card_data[key] not in (-1, ""):
208
+ # Only overwrite if detail value is also non-sentinel
209
+ if value in (-1, ""):
210
+ continue
211
+ card_data[key] = value
212
+ card_data = self.remove_unnecessary_fields(card_data)
213
+ self.result.append(card_data)
214
+ self.count_parsed_offers += 1
215
+
216
+ if self.with_saving_csv:
217
+ save_to_csv(self.result, str(self.file_path))
@@ -0,0 +1,94 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any
5
+
6
+ from playwright.sync_api import sync_playwright, Browser, BrowserContext, Page, Playwright, Error as PlaywrightError
7
+ from playwright_stealth import Stealth
8
+
9
+ from cian_parser.exceptions import BrowserNotInstalledError
10
+
11
+ logger = logging.getLogger("cian_parser")
12
+
13
+ USER_AGENT = (
14
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
15
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
16
+ )
17
+
18
+
19
+ class BrowserManager:
20
+ """Manages a single Playwright browser instance with stealth settings."""
21
+
22
+ def __init__(self, *, headless: bool = True, proxy: str | None = None):
23
+ self._headless = headless
24
+ self._proxy = proxy
25
+ self._playwright: Playwright | None = None
26
+ self._browser: Browser | None = None
27
+ self._context: BrowserContext | None = None
28
+ self._stealth = Stealth()
29
+ self._started = False
30
+
31
+ def start(self) -> None:
32
+ if self._started:
33
+ return
34
+
35
+ self._playwright = sync_playwright().start()
36
+
37
+ try:
38
+ self._browser = self._playwright.chromium.launch(
39
+ headless=self._headless,
40
+ args=["--disable-blink-features=AutomationControlled", "--no-sandbox"],
41
+ )
42
+ except PlaywrightError as exc:
43
+ self._playwright.stop()
44
+ self._playwright = None
45
+ if "Executable doesn't exist" in str(exc) or "browserType.launch" in str(exc):
46
+ raise BrowserNotInstalledError(
47
+ "Chromium browser is not installed. "
48
+ "Run `playwright install chromium` to install it."
49
+ ) from exc
50
+ raise
51
+
52
+ context_kwargs: dict[str, Any] = {
53
+ "user_agent": USER_AGENT,
54
+ "viewport": {"width": 1920, "height": 1080},
55
+ "locale": "ru-RU",
56
+ "timezone_id": "Europe/Moscow",
57
+ }
58
+ if self._proxy:
59
+ context_kwargs["proxy"] = {"server": self._proxy}
60
+
61
+ self._context = self._browser.new_context(**context_kwargs)
62
+ self._started = True
63
+ logger.info("Browser started (headless=%s)", self._headless)
64
+
65
+ def new_page(self) -> Page:
66
+ self._ensure_started()
67
+ page = self._context.new_page()
68
+ self._stealth.apply_stealth_sync(page)
69
+ return page
70
+
71
+ def navigate(self, page: Page, url: str) -> None:
72
+ page.goto(url, wait_until="domcontentloaded", timeout=30000)
73
+
74
+ def close(self) -> None:
75
+ if self._browser:
76
+ self._browser.close()
77
+ self._browser = None
78
+ if self._playwright:
79
+ self._playwright.stop()
80
+ self._playwright = None
81
+ self._context = None
82
+ self._started = False
83
+ logger.info("Browser closed")
84
+
85
+ def _ensure_started(self) -> None:
86
+ if not self._started:
87
+ self.start()
88
+
89
+ def __enter__(self) -> "BrowserManager":
90
+ self.start()
91
+ return self
92
+
93
+ def __exit__(self, *exc: object) -> None:
94
+ self.close()