0% found this document useful (0 votes)
3 views2 pages

JavaScript in Selenium Python CheatSheet

This cheat sheet provides essential JavaScript syntax and examples for use with Selenium in Python, including executing scripts, passing arguments, and common JavaScript snippets. It emphasizes best practices such as using 'return' for data retrieval and proper quote escaping. The document also includes examples for actions like scrolling, clicking elements, and retrieving page information.

Uploaded by

shrushti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

JavaScript in Selenium Python CheatSheet

This cheat sheet provides essential JavaScript syntax and examples for use with Selenium in Python, including executing scripts, passing arguments, and common JavaScript snippets. It emphasizes best practices such as using 'return' for data retrieval and proper quote escaping. The document also includes examples for actions like scrolling, clicking elements, and retrieving page information.

Uploaded by

shrushti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript in Selenium (Python) Cheat Sheet

Basic Syntax
• driver.execute_script(script, *args)
• driver.execute_async_script(script, *args)

- Pass Python args as arguments[0], arguments[1], etc.


- Use 'return' to get a value back from JS.

Examples
1. Run simple JS:
driver.execute_script("alert('Hello!');")

2. Get page title:


title = driver.execute_script("return [Link];")

3. Pass Python variable:


driver.execute_script("return 'Hi ' + arguments[0];", name)

4. Scroll page:
driver.execute_script("[Link](0, [Link]);")

5. Click element:
el = driver.find_element("id", "btn")
driver.execute_script("arguments[0].click();", el)

6. Set input value:


driver.execute_script("[Link]('input').value='test';")

7. Get all links:


driver.execute_script("return [Link]([Link]('a')).map(a=>[Link]);")

Async Script Syntax


driver.execute_async_script(''' var done = arguments[0]; setTimeout(function() { done("Async
Done!"); }, 2000); ''')

Common JS Snippets
- Scroll by pixels: [Link](0, 300)
- Scroll to element: arguments[0].scrollIntoView(true)
- Highlight: arguments[0].[Link]='2px solid red'
- Change style: arguments[0].[Link]='yellow'
- Return page text: return [Link]

Best Practices
✓ Always use return to get data back.
✓ Escape quotes properly when embedding JS.
✓ Use triple quotes (""" ... """) for multiline JS.
✓ Keep JS short and focused.
✓ Use execute_async_script for fetch/setTimeout/callbacks.

You might also like