首页 > 解决方案 > 如何在 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()会引发错误。

我怎样才能得到结果?

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

标签: javascriptpythonselenium

解决方案


在 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(谷歌浏览器)。HTML DOM

检查步骤:

Press F12 in Chrome-> 转到element部分 -> 执行CTRL + F-> 然后粘贴xpath并查看,如果您想要element的是否使用匹配节点突出显示。1/1


推荐阅读