@@ -1092,6 +1092,39 @@ async def wait_for(
10921092 await self .sleep (0.068 )
10931093 return item
10941094
1095+ async def set_attributes (self , selector , attribute , value ):
1096+ """This method uses JavaScript to set/update a common attribute.
1097+ All matching selectors from querySelectorAll() are used.
1098+ Example => (Make all links on a website redirect to Google):
1099+ self.set_attributes("a", "href", "https://google.com")"""
1100+ attribute = re .escape (attribute )
1101+ attribute = js_utils .escape_quotes_if_needed (attribute )
1102+ value = re .escape (value )
1103+ value = js_utils .escape_quotes_if_needed (value )
1104+ if selector .startswith (("/" , "./" , "(" )):
1105+ with suppress (Exception ):
1106+ selector = js_utils .convert_to_css_selector (selector , "xpath" )
1107+ css_selector = selector
1108+ css_selector = re .escape (css_selector ) # Add "\\" to special chars
1109+ css_selector = js_utils .escape_quotes_if_needed (css_selector )
1110+ js_code = (
1111+ """var $elements = document.querySelectorAll('%s');
1112+ var index = 0, length = $elements.length;
1113+ for(; index < length; index++){
1114+ $elements[index].setAttribute('%s','%s');}""" % (
1115+ css_selector ,
1116+ attribute ,
1117+ value ,
1118+ )
1119+ )
1120+ with suppress (Exception ):
1121+ await self .evaluate (js_code )
1122+
1123+ async def internalize_links (self ):
1124+ """All `target="_blank"` links become `target="_self"`.
1125+ This prevents those links from opening in a new tab."""
1126+ await self .set_attributes ('[target="_blank"]' , "target" , "_self" )
1127+
10951128 async def download_file (
10961129 self , url : str , filename : Optional [PathLike ] = None
10971130 ):
@@ -1336,8 +1369,8 @@ async def __on_a_cf_turnstile_page(self, source=None):
13361369 return True
13371370 return False
13381371
1339- async def __on_a_g_recaptcha_page (self , source = None ):
1340- await self .sleep (0.4 )
1372+ async def __on_a_g_recaptcha_page (self , * args , ** kwargs ):
1373+ await self .sleep (0.4 ) # reCAPTCHA may need a moment to appear
13411374 source = await self .get_html ()
13421375 if (
13431376 (
0 commit comments