[英]How to click an element with Javascript in Selenium Python
Using selenium, I would like to have a result of an click action on an element in html (HTML4).使用 selenium,我希望对 html (HTML4) 中的元素进行单击操作的结果。
The dom in the html is like this html中的dom是这样的
<A HREF="javascript:open_login_page();">
<IMG NAME="login_button" SRC="hoge.jpg" alt="login"></A>
It seems my Python script successfully obtains the element.看来我的 Python 脚本成功获取了该元素。
Using the obtained element a_element
,使用获得的元素
a_element
,
a_element.get_attribute('href')
returns返回
javascript:open_login_page();
However, a_element.click()
raises an error.但是,
a_element.click()
会引发错误。
How can I have the result?我怎样才能得到结果?
The expected result is to have another window popup.预期的结果是有另一个窗口弹出。
There are basically 4 ways to click in Selenium.基本上有 4 种方法可以在 Selenium 中单击。
I will use this xpath我将使用这个 xpath
//IMG[@NAME='login_button']//parent::A
Code trial 1 :代码试用1:
time.sleep(5)
driver.find_element_by_xpath("//IMG[@NAME='login_button']//parent::A").click()
Code trial 2 :代码试用2:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//IMG[@NAME='login_button']//parent::A"))).click()
Code trial 3 :代码试用3:
time.sleep(5)
button = driver.find_element_by_xpath("//IMG[@NAME='login_button']//parent::A")
driver.execute_script("arguments[0].click();", button)
Code trial 4 :代码试用4:
time.sleep(5)
button = driver.find_element_by_xpath("//IMG[@NAME='login_button']//parent::A")
ActionChains(driver).move_to_element(button).click().perform()
Imports :进口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
PS : Please check in the dev tools
(Google chrome) if we have unique entry in HTML DOM
or not. PS:如果我们在
HTML DOM
是否有唯一条目,请检查dev tools
(谷歌浏览器)。
Steps to check:检查步骤:
Press F12 in Chrome
-> go to element
section -> do a CTRL + F
-> then paste the xpath
and see, if your desired element
is getting highlighted with 1/1
matching node. Press F12 in Chrome
-> 转到element
部分 -> 执行CTRL + F
-> 然后粘贴xpath
并查看您想要的element
是否被1/1
匹配节点突出显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.