Reputation: 1413
I am working to get the element details while clicking on that element inside the selenium web driver in python by executing a javascript function on the page.
But it is not working as I expected, even I have used the async method to get the element details from javascript to python. But I still can't able to get the element details in serverside python code.
Please provide a better solution for this case.
sample code
@asyncio.coroutine
def mouseevent(driver):
while true:
mouse =driver.execute_script('''
var x= onclick = function(e){
return e.target;
}
''')
print(mouse)
driver=webdriver.Chrome(Chrome)
driver.implicitly_wait(30)
driver.maximize_window()
driver.get("https://www.google.com/")
loop = asyncio.get_event_loop()
tasks = [
asyncio.ensure_future(mouseevent(driver))]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
Thanks in Advance.
Upvotes: 1
Views: 417
Reputation: 142681
Maybe there is better method but this code works for me.
First I create variable window.x
with default value at start so I can check its value all the time - even if I don't click any element.
driver.execute_script('window.x = null;')
Later I assign to body
function which will be executed when I click body
- it will assign value to window.x
driver.execute_script('document.body.addEventListener("click", function(e) { window.x = e.target;})')
And in loop I only check value in this variable.
while True:
print(driver.execute_script('return window.x'))
time.sleep(0.5)
It would need to check if value was changed between loop or it should run function which copy value from window.x
to ie. window.y
, next it clearn window.x
and it returns window.y
- this way it will get value only once.
while True:
print(driver.execute_script('window.y = window.x; window.x = null; return window.y'))
time.sleep(0.5)
import selenium.webdriver
import time
url = 'https://stackoverflow.com'
driver = selenium.webdriver.Firefox()
driver.get(url)
driver.execute_script('window.x = null;')
driver.execute_script('document.body.addEventListener("click", function(e) { window.x = e.target;})')
while True:
print(driver.execute_script('window.y = window.x; window.x = null; return window.y'))
time.sleep(0.5)
EDIT: I found answers which should better resolve problem: Javascript - Track mouse position
Upvotes: 1