javascript - 如何在 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
(谷歌浏览器)。HTML DOM
检查步骤:
Press F12 in Chrome
-> 转到element
部分 -> 执行CTRL + F
-> 然后粘贴xpath
并查看,如果您想要element
的是否使用匹配节点突出显示。1/1
推荐阅读
- spring-boot - Springboot 配置属性范围或数组
- tcl - 如何从项目打开的 url 链接中删除端口号 :8000?
- spring - Thymeleaf 发布表单不提交数据
- c++builder - DBX 错误:驱动程序无法正确初始化
- hibernate - how to write a method using hibernate which returns boolean
- c# - 在单元测试用例中捕获抛出的异常的问题
- angular - 如何将数据从角度材料对话框传递到父组件?
- python - 在 Django 2.0 中使用 URL
- javascript - Detect Swipe without affecting click event
- ansible - 为什么“拒绝”过滤器在 ansible 中不起作用