如何在Selenium Python中使用Javascript单击元素



使用selenium,我想在html (HTML4)中对元素进行单击操作的结果。

html中的dom是这样的

<A HREF="javascript:open_login_page();">
<IMG NAME="login_button" SRC="hoge.jpg" alt="login"></A>

似乎我的Python脚本成功地获得了元素。

使用获得的元素a_element

a_element.get_attribute('href')

返回
javascript:open_login_page();

但是,a_element.click()抛出一个错误。

我怎样才能得到结果?

预期结果是有另一个窗口弹出。

在Selenium中基本上有4种点击方式。

我将使用xpath

//IMG[@NAME='login_button']//parent::A

代码试验1:

time.sleep(5)
driver.find_element_by_xpath("//IMG[@NAME='login_button']//parent::A").click()

代码试验2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//IMG[@NAME='login_button']//parent::A"))).click()

代码试验3:

time.sleep(5)
button = driver.find_element_by_xpath("//IMG[@NAME='login_button']//parent::A")
driver.execute_script("arguments[0].click();", button)

代码试验4:

time.sleep(5)
button = driver.find_element_by_xpath("//IMG[@NAME='login_button']//parent::A")
ActionChains(driver).move_to_element(button).click().perform()

进口:

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:请检查dev tools(Google chrome),如果我们有唯一的是否进入HTML DOM

检查步骤:

Press F12 in Chrome->去element节->做一个CTRL + F->然后粘贴xpath,看看你想要的element是否得到高亮显示1/1匹配节点

最新更新