问题
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()
But what to do if I need to modify the content of the variable where I have to write the variable inside the script?
More specifically, I am facing the following problem:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Here in this code, I have to write the document.body.scrollHeight
inside the script. But I want to add a random factor [0-1]
to be multiplied with document.body.scrollHeight
such that the scrolling doesn't seem to be automated. For this reason, I tried the following:
import numpy as np
factor = float(np.random.uniform(0, 1))
driver.execute_script("window.scrollTo(0, %s);" % str(np.int(float(document.body.scrollHeight) * factor)))
But this doesn't work. As document.body.scrollHeight
is outside, hence, the program doesn't find document
. So I want to introduce a custom variable factor
inside the script. How to do that?
回答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.
来源:https://stackoverflow.com/questions/65274678/how-to-introduce-custom-variables-inside-driver-execute-scripthere