Skip to content Skip to sidebar Skip to footer

How To Introduce Custom Variable(s) Inside Driver.execute_script()?

For a web driver we can execute JavaScript code which includes custom variable like this: driver.execute_script('alert('%s')' % variable) # an example introducing variable in alert

Solution 1:

See the selenium docs here.

To pass variables into the execute script you use comma. This bit:

execute_script(script, *args)¶

Synchronously Executes JavaScript in the current window/frame.

Args: script: The JavaScript to execute. *args: Any applicable arguments for your JavaScript. Usage: driver.execute_script(‘return document.title;’)

When you accessing variables you then use arguments[x] to access (indexed at 0). A good example and a common one you'll find is: execute_script("arguments[0].click()" , element). You can see script then comma then the element you want to click. But you can pass in as many as you like.

Onto your problem.

There are a couple of ways to get the scroll height. You can get the body scroll height from selenium or from js.

Doing it in js (so it matches your current approach) you can do it in 2 calls.

BodyScrollHeight = driver.execute_script("return document.body.scrollHeight;") 

factor = float(np.random.uniform(0, 1))
driver.execute_script("window.scrollTo(0, %s);" % str(np.int(float(BodyScrollHeight) * factor)))

or - using the comma approach.

BodyScrollHeight = 100 #calculate your factor here 
driver.execute_script("window.scrollTo(0, arguments[0]);", BodyScrollHeight) 

I've not had chance to run this but if it doesn't work let me know and I'll look again.

Post a Comment for "How To Introduce Custom Variable(s) Inside Driver.execute_script()?"