Selenium 忽略 WebDriverWait 并执行操作

问题描述 投票:0回答:1

测试有多次点击,这些点击会重定向到其他页面,因此我在那里添加了一些显式等待,但是当执行测试时,Selenium 会忽略两个等待之一并执行点击。只有当下一页已经加载时才会执行显式等待,当然会引发 TimeoutException 因为它无法在那里找到元素。另外我需要提到的是,有时测试可以正确执行,但我认为这是因为页面已及时加载。

def test_two(browser):
    browser.get('http://localhost/index.php?route=common/home&language=en-gb')
    macbook = browser.find_element(By.CSS_SELECTOR, "#content > div.row > div:nth-child(1) > form > div > div.content > div.button-group > button:nth-child(3)")
    iphone = browser.find_element(By.CSS_SELECTOR, "#content > div.row > div:nth-child(2) > form > div > div.content > div.button-group > button:nth-child(3)")

    browser.execute_script("arguments[0].click();", macbook)
    browser.execute_script("arguments[0].click();", iphone)
    browser.get('http://localhost/index.php?route=product/compare&language=en-gb')

    delete_macbook = WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#content > table > tbody:nth-child(7) > tr > td:nth-child(2) > form > a")))
    browser.execute_script("arguments[0].click();", delete_macbook)
    delete_iphone = WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.LINK_TEXT, "Remove")))
    browser.execute_script("arguments[0].click();", delete_iphone)

我还尝试在 Firefox(最初是 Chrome)中运行此测试,它正确地满足了每个显式等待。那么可能是浏览器或驱动程序问题吗?

-新手写的

python selenium-webdriver pytest webdriverwait
1个回答
0
投票

要单击任何 clickable 元素而不是 presence_of_element_ located(),理想情况下,您需要为 element_to_be_clickable() 引入 WebDriverWait,并且您可以使用以下任一 定位器策略

def test_two(browser):
    browser.get('http://localhost/index.php?route=common/home&language=en-gb')
    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#content > div.row > div:nth-child(1) > form > div > div.content > div.button-group > button:nth-child(3)"))).click()
    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#content > div.row > div:nth-child(2) > form > div > div.content > div.button-group > button:nth-child(3)"))).click()

    browser.get('http://localhost/index.php?route=product/compare&language=en-gb')
    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#content > table > tbody:nth-child(7) > tr > td:nth-child(2) > form > a"))).click()
    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Remove"))).click()
© www.soinside.com 2019 - 2024. All rights reserved.