Skip to content

Commit bdd3834

Browse files
committed
Refactor UC Mode
1 parent 0a4a49b commit bdd3834

File tree

6 files changed

+46
-52
lines changed

6 files changed

+46
-52
lines changed

seleniumbase/undetected/__init__.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,8 @@
3333

3434

3535
class Chrome(selenium.webdriver.chrome.webdriver.WebDriver):
36-
"""
37-
Controls chromedriver to drive a browser.
38-
The driver gets downloaded automatically.
39-
40-
*** Methods ***
41-
---------------
42-
43-
* reconnect()
44-
This can be useful when sites use heavy detection methods:
45-
- Stops the chromedriver service that runs in the background.
46-
- Starts the chromedriver service that runs in the background.
47-
- Recreates the session.
48-
"""
36+
"""Controls chromedriver to drive a browser.
37+
The driver gets downloaded automatically."""
4938
_instances = set()
5039
session_id = None
5140
debug = False
@@ -66,7 +55,7 @@ def __init__(
6655
suppress_welcome=True,
6756
use_subprocess=True,
6857
debug=False,
69-
**kw
58+
**kw,
7059
):
7160
"""
7261
Starts the Chrome service and creates a new instance of chromedriver.
@@ -216,7 +205,11 @@ def __init__(
216205
language = locale.getlocale()[0].replace("_", "-")
217206
except Exception:
218207
pass
219-
if not language:
208+
if (
209+
not language
210+
or "English" in language
211+
or "United States" in language
212+
):
220213
language = "en-US"
221214
options.add_argument("--lang=%s" % language)
222215
if not options.binary_location:
@@ -245,9 +238,14 @@ def __init__(
245238
import json
246239

247240
with open(
248-
os.path.join(user_data_dir, "Default/Preferences"),
249-
encoding="latin1",
241+
os.path.join(
242+
os.path.abspath(user_data_dir),
243+
"Default",
244+
"Preferences",
245+
),
246+
encoding="utf-8",
250247
mode="r+",
248+
errors="ignore",
251249
) as fs:
252250
config = json.load(fs)
253251
if (
@@ -405,6 +403,10 @@ def tab_list(self):
405403
return [PageElement(o) for o in retval]
406404

407405
def reconnect(self, timeout=0.1):
406+
"""This can be useful when sites use heavy detection methods:
407+
- Stops the chromedriver service that runs in the background.
408+
- Starts the chromedriver service that runs in the background.
409+
- Recreates the session. """
408410
try:
409411
self.service.stop()
410412
except Exception as e:

seleniumbase/undetected/cdp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def tab_close_last_opened(self):
7474
opentabs = [s for s in sessions if s["type"] == "page"]
7575
return self.post(self.endpoints["close"].format(id=opentabs[-1]["id"]))
7676

77-
async def send(self, method, params): # noqa
77+
async def send(self, method, params):
7878
import websockets
7979

8080
self._reqid += 1

seleniumbase/undetected/dprocess.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,17 @@
1111

1212

1313
def start_detached(executable, *args):
14-
"""
15-
Starts a fully independent subprocess with no parent.
14+
"""Starts a fully independent subprocess with no parent.
1615
:param executable: executable
1716
:param args: arguments to the executable,
1817
eg: ["--param1_key=param1_val", "-vvv"]
19-
:return: pid of the grandchild process
20-
"""
18+
:return: pid of the grandchild process """
2119
import multiprocessing
2220

2321
reader, writer = multiprocessing.Pipe(False) # Create pipe
24-
# Do not keep reference
2522
multiprocessing.Process(
2623
target=_start_detached,
27-
args=(executable, *args), # noqa
24+
args=(executable, *args),
2825
kwargs={"writer": writer},
2926
daemon=True,
3027
).start()

seleniumbase/undetected/options.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ def handle_prefs(self, user_data_dir):
5151
prefs_file = os.path.join(default_path, "Preferences")
5252
try:
5353
if os.path.exists(prefs_file):
54-
with open(prefs_file, encoding="utf-8", mode="r") as f:
54+
with open(
55+
prefs_file, encoding="utf-8", mode="r", errors="ignore"
56+
) as f:
5557
undot_prefs = self._merge_nested(
5658
json.load(f), undot_prefs
5759
)

seleniumbase/undetected/patcher.py

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,13 @@ class Patcher(object):
3939
data_path = os.path.abspath(os.path.expanduser(downloads_folder))
4040

4141
def __init__(self, executable_path=None, force=False, version_main=0):
42-
"""
43-
Args:
44-
executable_path: None = automatic
45-
A full file path to the chromedriver executable
46-
force: False
47-
Terminate processes which are holding lock
48-
version_main: 0 = auto
49-
Specify main chrome version (rounded, ex: 82)
50-
"""
42+
"""Args:
43+
executable_path: None = automatic
44+
A full file path to the chromedriver executable
45+
force: False
46+
Terminate processes which are holding lock
47+
version_main: 0 = auto
48+
Specify main chrome version (rounded, ex: 82) """
5149
self.force = force
5250
self.executable_path = None
5351
prefix = "undetected"
@@ -89,17 +87,17 @@ def auto(self, executable_path=None, force=False, version_main=None):
8987
self.force = force
9088
try:
9189
os.unlink(self.executable_path)
92-
except PermissionError: # noqa
90+
except PermissionError:
9391
if self.force:
9492
self.force_kill_instances(self.executable_path)
9593
not_force = not self.force
9694
return self.auto(force=not_force)
9795
try:
9896
if self.is_binary_patched():
9997
return True # Running AND patched
100-
except PermissionError: # noqa
98+
except PermissionError:
10199
pass
102-
except FileNotFoundError: # noqa
100+
except FileNotFoundError:
103101
pass
104102
release = self.fetch_release_number()
105103
self.version_main = release.split(".")[0]
@@ -122,10 +120,8 @@ def fetch_release_number(self):
122120
return urlopen(self.url_repo + path).read().decode()
123121

124122
def fetch_package(self):
125-
"""
126-
Downloads chromedriver from source.
127-
:return: path to downloaded file
128-
"""
123+
"""Downloads chromedriver from source.
124+
:return: path to downloaded file """
129125
from urllib.request import urlretrieve
130126

131127
u = "%s/%s/%s" % (
@@ -135,13 +131,11 @@ def fetch_package(self):
135131
return urlretrieve(u)[0]
136132

137133
def unzip_package(self, fp):
138-
"""
139-
:return: path to unpacked executable
140-
"""
134+
""" :return: path to unpacked executable """
141135
logger.debug("unzipping %s" % fp)
142136
try:
143137
os.unlink(self.zip_path)
144-
except (FileNotFoundError, OSError): # noqa
138+
except (FileNotFoundError, OSError):
145139
pass
146140
os.makedirs(self.zip_path, mode=0o755, exist_ok=True)
147141
with zipfile.ZipFile(fp, mode="r") as zf:
@@ -163,10 +157,9 @@ def unzip_package(self, fp):
163157

164158
@staticmethod
165159
def force_kill_instances(exe_name):
166-
"""
160+
""" Terminate instances of UC.
167161
:param: executable name to kill, may be a path as well
168-
:return: True on success else False
169-
"""
162+
:return: True on success else False """
170163
exe_name = os.path.basename(exe_name)
171164
if IS_POSIX:
172165
r = os.system("kill -f -9 $(pidof %s)" % exe_name)
@@ -288,8 +281,8 @@ def __del__(self):
288281
% self.executable_path
289282
)
290283
break
291-
except (OSError, RuntimeError, PermissionError): # noqa
284+
except (OSError, RuntimeError, PermissionError):
292285
time.sleep(0.1)
293286
continue
294-
except FileNotFoundError: # noqa
287+
except FileNotFoundError:
295288
break

seleniumbase/undetected/reactor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def run(self):
4141
except Exception as e:
4242
logger.warning("Reactor.run() => %s", e)
4343

44-
async def _wait_service_started(self): # noqa
44+
async def _wait_service_started(self):
4545
while True:
4646
with self.lock:
4747
if (
@@ -53,7 +53,7 @@ async def _wait_service_started(self): # noqa
5353
else:
5454
break
5555

56-
async def listen(self): # noqa
56+
async def listen(self):
5757
while self.running:
5858
await self._wait_service_started()
5959
await asyncio.sleep(1)

0 commit comments

Comments
 (0)