selenium中的WebElement.click

selenium中的WebElement.click,第1张

       selenium中的使用WebElement.click()出现失效是个老大难的问题,在stackoverflow上也有不少人在抱怨,说从3.0到4.1都没有解决。抛开html页面元素相互遮盖和元素定位不准的情况,经过测试,发现主要出现在chrome 和edge浏览器上,同样一个网站,chrome浏览器点击失效但是使用firefox正常。网上的资料提出了不少的解决办法,但是有些是不靠谱的 ,现一一总结如下:

1.WebElement.click()点击成功,但是程序挂起,不能运行下一步。

       这种情况浏览器chrome访问一些使用json、http restful生成页面元素的网站上经常会遇到,现象是点击页面成功,但是程序挂起,就是click()一直不返回,程序不能运行下一条程序语言。
       经过调试跟踪发现,由于selenium使用的chrome webdriver使用的是基于JSON Wire Protocol Specification协议,在提交点击动作后,会等待服务器的响应返回,服务器响应返回状态值,才算click()动作结束。如果服务器没有返回click()结果状态,selenium会一直挂起。但是firefox使用的协议不是JSON Wire Protocol Specification,所以不会存在这个问题。

2.使用execute_script("arguments[0].click()", we)方式解决

        经过试验是兼容性最好的一种方法,在firefox和chrome均能有效的执行,有时候也会出现失效,基本上能较为有效的成功解决click()挂起和失效的问题,stackoverflow上基本上都是推荐这种方式。但是按照stackoverflow上一个人说法:在迫不得已的情况下,不要使用这种方式,因为这种做,虽然不影响程序运行结果,但是没有达到自动化测试的目的,例如:移动鼠标、点击动作等。代码如下:

from typing import NoReturn
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support import wait
from selenium.common.exceptions import WebDriverException

browser_type='chrome'

def click_element(browser:webdriver, we) -> NoReturn:
    if browser_type == "firefox":
        we.click()
    elif browser_type == "chrome":
        browser.execute_script("arguments[0].click()", we)

3.使用ActionChains方式

        查看源代码,WebElement.click()就是ActionChains封装版
例如:下面这句语句
 

ActionChains(driver).move_to_element_with_offset(element, 5, 5).click().perform() 

等同于
 

element.click()


所以使用ActionChains不能解决click()失效的问题。

测试环境:
python:3.7
selenium:4.1
chrome98
firefox100
chromedriver 98
geckodriver 0.30
Windows server 2016
参考资料
Selenium4.1的官网API
https://www.selenium.dev/selenium/docs/api/py/api.html
https://github.com/SeleniumHQ/Selenium

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/904619.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-15
下一篇2022-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存