【问题标题】:selenium webdriverwait does not reset timer in for loop | pythonselenium webdriverwait 不会在 for 循环中重置计时器Python
【发布时间】:2021-03-24 04:33:02
【问题描述】:

我正在使用 python3.8.5 和 selenium3.141.0 来自动化登录过程。要使用 css 选择器定位登录按钮,但在我的测试中,选择器可以更改(我对此有点模糊 - 与页面加载方式有关的动态??)。

我目前的解决方案是遍历我观察到的 css 选择器列表(它们确实重复):

driver = webdriver.Chrome(options=options)
success = True
errorMSG = ""

for loginClickID in paper.loginClickID:
        wait = WebDriverWait(driver, 12)
        try:
            wait.until(
            EC.presence_of_element_located(By.CSS_SELECTOR, loginClickID)
            ) 
        except Exception as e:  
            log("\nFailed to see click-to-login element: " + loginClickID + "\nHTML output shown below:\n\n" + driver.page_source)
            success = False
                errorMSG = e

if not success:
        response = driver.page_source
        driver.quit()
        return f"{paper.brand} login_fail\nLoginClickID: {loginClickID}\nNot found in:\n{response}\n{errorMSG}\n"

我正在为循环的每次迭代创建一个新的WebDriverWait() 对象。但是,当我调试代码并手动跳过它时,第二次进入循环时,wait.until() 方法立即退出,甚至没有抛出异常(这很奇怪,对吗?)并完全退出循环(css选择器列表有 2 个元素)

我的想法是 wait.until() 计时器没有重置?

我尝试使用driver.refresh() 重新加载页面,并在except: 部分使用time.sleep(1) 休眠python 代码,希望这可能有助于休息——它没有...

我已将所有 ChromeDriver 选项都包含在上下文中:

options = Options()
    # options.add_argument("--headless")
    options.add_argument("window-size=1400,1500")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    options.add_argument("enable-automation")
    options.add_argument("--disable-infobars")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("start-maximized")
    options.add_argument("--disable-browser-side-navigation")

我正在使用: 谷歌浏览器 80.0.3987.106 & ChromeDriver 80.0.3987.106

有什么建议吗?

【问题讨论】:

    标签: python selenium google-chrome authentication selenium-chromedriver


    【解决方案1】:

    为什么使用

    css 选择器

    正如你所说,这是明显的动态 - 它们会改变..

    为什么不使用 Xpath?

    xpath_email = "//input[@type='email']"
    xpath_password = "//input[@type='password']"
    
    driver.find_element_by_xpath(xpath_email)
    time.sleep(1)
    driver.find_element_by_xpath(xapth_password)
    

    这些显然是通用的 xpath,但您可以在任何登录页面上找到它们,并进行相应的更改。

    这样,无论是什么测试用例,你的逻辑都会起作用。

    【讨论】:

    • 我的测试表明,如果 html 元素没有 id 字段,xpath 也可以是动态的...
    猜你喜欢
    • 1970-01-01
    • 2010-11-14
    • 2019-12-05
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多