Selenium execute Javascript script using parameters and return values

Selenium can be used in drvier.execute_script () to execute Javascript script supports multi-line statements.
Javascript can be achieved using the following functions:

  • Remove elements hide, disable, read-only attribute restrictions
  • Add the element id or highlight style
  • Page scrolling
  • Rich text input box (HTML injection)
  • Get information page

Use Javascript parameters

In use Javascript statement, further parameters may be dynamically passed objects or elements, Javascript placeholder used in the statement "argument [n]" denotes to take the first several parameters, such as:

js = "arguments[0].setAttribute('style', arguments[1]);"

Here two buried parameters, one element of the object, the other is a pattern string.

element = driver.find_element_by_id("kw")
style = "background: red; border: 2px solid yellow;"

When a script executes, in order to carry parameters:

driver.execute_script(js, element, style)

Javascript obtain the return value

Plus return the words in Javascript statements, such as access to page height:

js = 'return document.documentElement.scrollHeight;'

The execution can get after its return value:

page_height = driver.execute_script(js)

Complete example

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')

js = 'arguments[0].setAttribute("style", arguments[1]);'
element = driver.find_element('id', 'kw')
style = 'background: red; border: 2px solid yellow;'
driver.execute_script(js, element, style)

page_height = driver.execute_script('return document.documentElement.scrollHeight;')
print(page_height)

time.sleep(3)
driver.quit()

Run results shown in Figure:

Print Results:

890

Guess you like

Origin www.cnblogs.com/superhin/p/12604080.html