selenium.webdriver.remote.script#
The supported script API, returned by driver.script.
Pinned scripts, script execution and console, JavaScript-error and DOM-mutation
handlers. Nothing here hands back a protocol type: results are plain Python
values and elements come back as WebElement, as with execute_script.
See SeleniumHQ/selenium
Functions
|
Convert a script result into the Python value |
|
Convert a Python value into a script argument. |
Classes
|
A console message observed in the browser. |
|
Represents a DOM mutation event from add_dom_mutation_handler. |
|
Identifier of a pinned script, as returned by |
|
Pinned scripts, script execution and script event handlers. |
|
A JavaScript error observed in the browser. |
|
Result of executing code with a pinned script in scope, without raising on failure. |
- class ScriptError(message=None, source=None, line_number=None, column_number=None, stack_trace=None, timestamp=None)[source]#
Bases:
objectA JavaScript error observed in the browser.
- Parameters:
message (str | None)
source (str | None)
line_number (int | None)
column_number (int | None)
stack_trace (str | None)
timestamp (float | None)
- message#
The error message.
- Type:
str | None
- source#
Source file/URL where the error occurred (top stack frame).
- Type:
str | None
- line_number#
Line number of the error.
- Type:
int | None
- column_number#
Column number of the error.
- Type:
int | None
- stack_trace#
Formatted stack trace, one
at function (url:line:col)line per frame.- Type:
str | None
- timestamp#
Time the entry was generated, in milliseconds since epoch.
- Type:
float | None
- message: str | None = None#
- source: str | None = None#
- line_number: int | None = None#
- column_number: int | None = None#
- stack_trace: str | None = None#
- timestamp: float | None = None#
- class ConsoleMessage(level=None, text=None, source=None, line_number=None, column_number=None, stack_trace=None, timestamp=None, method=None, args=None)[source]#
Bases:
objectA console message observed in the browser.
- Parameters:
level (str | None)
text (str | None)
source (str | None)
line_number (int | None)
column_number (int | None)
stack_trace (str | None)
timestamp (float | None)
method (str | None)
args (list[Any] | None)
- level#
Console level (
debug,info,warnorerror).- Type:
str | None
- text#
The console message text.
- Type:
str | None
- source#
Source file/URL the message originated from (top stack frame).
- Type:
str | None
- line_number#
Line number where the message originated.
- Type:
int | None
- column_number#
Column number where the message originated.
- Type:
int | None
- stack_trace#
Formatted stack trace where available.
- Type:
str | None
- timestamp#
Time the entry was generated, in milliseconds since epoch.
- Type:
float | None
- method#
The console method used (e.g.
log,warn).- Type:
str | None
- args#
The raw arguments passed to the console call.
- Type:
list[Any] | None
- level: str | None = None#
- text: str | None = None#
- source: str | None = None#
- line_number: int | None = None#
- column_number: int | None = None#
- stack_trace: str | None = None#
- timestamp: float | None = None#
- method: str | None = None#
- args: list[Any] | None = None#
- class ScriptResult(value=None, error=None, realm=None)[source]#
Bases:
objectResult of executing code with a pinned script in scope, without raising on failure.
- Parameters:
value (Any | None)
error (ScriptError | None)
realm (str | None)
- value#
The value the code returned, converted as
execute_scriptconverts it, orNonewhen the code raised.- Type:
Any | None
- error#
A
ScriptErrordescribing the failure, orNoneon success.- Type:
- realm#
Deprecated; an implementation detail that will be removed.
- Type:
str | None
- value: Any | None = None#
- error: ScriptError | None = None#
- realm: str | None = None#
- class DomMutation(element_id=None, attribute_name=None, current_value=None, old_value=None, type=None, target=None, added_nodes=<factory>, removed_nodes=<factory>)[source]#
Bases:
objectRepresents a DOM mutation event from add_dom_mutation_handler.
- Parameters:
element_id (str | None)
attribute_name (str | None)
current_value (str | None)
old_value (str | None)
type (str | None)
target (str | None)
added_nodes (list[Any])
removed_nodes (list[Any])
- element_id#
The
data-__webdriver_idattribute value set on the mutated element by the MutationObserver. Use this to locate the element from the main thread if needed. ForcharacterDatamutations this identifies the parent element of the text node.- Type:
str | None
- attribute_name#
The name of the changed attribute (
attributesmutations only).- Type:
str | None
- current_value#
The value after the mutation (attribute value or character data;
Noneif the attribute was removed).- Type:
str | None
- old_value#
The value before the mutation.
- Type:
str | None
- type#
The mutation type:
attributes,childListorcharacterData.- Type:
str | None
- target#
Same identifier as
element_id; named per the cross-binding API design.- Type:
str | None
- added_nodes#
Node descriptors added by a
childListmutation. Element descriptors carrynodeType/nodeName/id(adata-__webdriver_idvalue); other nodes carrynodeType/nodeName/value.- Type:
list[Any]
- removed_nodes#
Node descriptors removed by a
childListmutation.- Type:
list[Any]
- element_id: str | None = None#
- attribute_name: str | None = None#
- current_value: str | None = None#
- old_value: str | None = None#
- type: str | None = None#
- target: str | None = None#
- added_nodes: list[Any]#
- removed_nodes: list[Any]#
- class PinnedScript(script_id, source=None, realm=None)[source]#
Bases:
strIdentifier of a pinned script, as returned by
driver.script.pin().Subclasses
strso existing code that treats the return value ofpin()as a plain script ID string keeps working. Pass it todriver.script.execute()to run code with the pinned source in scope, and todriver.script.unpin()to remove it.- Parameters:
script_id (str)
source (str | None)
realm (str | None)
- property id: str#
The unique identifier of the pinned script.
- property source: str | None#
The JavaScript source the script was pinned with.
- property realm: str | None#
an implementation detail that is never populated by
pin().- Type:
Deprecated
- capitalize()#
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()#
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)#
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int#
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')#
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool#
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)#
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int#
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str#
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str#
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int#
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()#
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()#
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()#
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()#
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()#
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()#
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()#
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()#
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()#
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()#
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()#
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()#
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)#
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)#
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()#
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)#
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()#
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)#
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)#
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)#
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)#
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int#
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int#
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)#
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)#
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)#
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)#
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)#
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)#
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool#
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)#
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()#
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()#
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)#
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()#
Return a copy of the string converted to uppercase.
- zfill(width, /)#
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- serialize_argument(value)[source]#
Convert a Python value into a script argument.
Accepts what
execute_scriptaccepts:None,bool,int,float(includingNaNand infinities),str, lists and tuples, dicts,datetime.datetime,WebElementandShadowRoot.- Parameters:
value (Any)
- Return type:
Any
- deserialize_result(value, driver=None)[source]#
Convert a script result into the Python value
execute_scriptwould return.Primitives map to their Python types, arrays and sets to lists, objects and maps to dicts, element nodes to
WebElementand shadow roots toShadowRoot(when a driver is given) and windows to their window handle. Values with no JSON form, such as functions, promises and symbols, becomeNone.- Parameters:
value (Any)
driver (WebDriver | None)
- Return type:
Any
- class Script(script, driver=None)[source]#
Bases:
objectPinned scripts, script execution and script event handlers.
Obtain it with
driver.script; do not construct it directly.- Parameters:
script (Any)
driver (WebDriver | None)
- pin(function_declaration)[source]#
Pin a script so it runs in every new document and can be reused by
execute().- Parameters:
function_declaration (str) – The JavaScript function declaration to pin, e.g.
"() => { window.helper = () => 42 }".- Returns:
A
PinnedScriptto pass toexecute()andunpin().- Return type:
- unpin(script_id)[source]#
Remove a pinned script.
- Parameters:
script_id (PinnedScript | str) – The
PinnedScriptreturned bypin().- Return type:
None
- execute(function_declaration, *args, context_id=None)[source]#
Execute JavaScript in the current window and return its result.
Arguments and return values are converted as by
execute_script:WebElementarguments are passed to the page as elements, and elements in the result come back asWebElement.- Parameters:
function_declaration (str | PinnedScript) – The function to run, e.g.
"(a, b) => a + b", or aPinnedScriptreturned bypin().*args (Any) – Arguments passed to the function. When
function_declarationis aPinnedScript, the single argument is the code to run with the pinned source in scope, e.g."return helper();".context_id (str | None) – The window handle to run in. Defaults to the current window.
- Returns:
The function’s return value. When
function_declarationis aPinnedScript, aScriptResultinstead, which reports failures throughScriptResult.errorrather than raising.- Raises:
JavascriptException – If the script throws.
- Return type:
Any
Example
total = driver.script.execute(“(a, b) => a + b”, 1, 2)
- add_console_handler(callback)[source]#
Add a handler called with a
ConsoleMessagefor each console message.- Returns:
An id for
remove_console_handler().- Parameters:
callback (Callable[[ConsoleMessage], Any])
- Return type:
int
- remove_console_handler(callback_id)[source]#
Remove a handler added by
add_console_handler().- Parameters:
callback_id (int)
- Return type:
None
- clear_console_handlers()[source]#
Remove every console handler, including those added by
add_console_message_handler().- Return type:
None
- add_console_message_handler(callback)[source]#
Add a handler called with a console log entry for each console message.
For payloads carrying source URL and line/column numbers, see
add_console_handler().- Returns:
An id for
remove_console_message_handler().- Parameters:
callback (Callable)
- Return type:
int
- remove_console_message_handler(callback_id)[source]#
Remove a handler added by
add_console_message_handler().- Parameters:
callback_id (int)
- Return type:
None
- add_error_handler(callback)[source]#
Add a handler called with a
ScriptErrorfor each uncaught JavaScript error.- Returns:
An id for
remove_error_handler().- Parameters:
callback (Callable[[ScriptError], Any])
- Return type:
int
- remove_error_handler(callback_id)[source]#
Remove a handler added by
add_error_handler().- Parameters:
callback_id (int)
- Return type:
None
- clear_error_handlers()[source]#
Remove every JavaScript error handler, including those added by
add_javascript_error_handler().- Return type:
None
- add_javascript_error_handler(callback)[source]#
Add a handler called with a JavaScript log entry for each uncaught JavaScript error.
For payloads carrying source URL and line/column numbers, see
add_error_handler().- Returns:
An id for
remove_javascript_error_handler().- Parameters:
callback (Callable)
- Return type:
int
- remove_javascript_error_handler(callback_id)[source]#
Remove a handler added by
add_javascript_error_handler().- Parameters:
callback_id (int)
- Return type:
None
- add_dom_mutation_handler(callback, mutation_types=None)[source]#
Add a handler called with a
DomMutationfor each observed DOM mutation.- Parameters:
callback (Callable[[DomMutation], Any]) – Function called with a
DomMutation.mutation_types (str | Iterable[str] | None) – Any of
attributes,childListandcharacterData, as a string or an iterable of strings. Defaults to("attributes",).
- Returns:
An id for
remove_dom_mutation_handler().- Return type:
int