Python Selenium webdriver 不能超时异常:等待元素时的消息



我正在使用PythonSelenium来自动化测试用例。问题是当我到达test_press_add_to_cart时,Webdriver看不到带有xpath的元素:

//*[@id="fybAddCartEvent"]

可能有什么问题?

例外情况是:

"超时异常:消息">

元素的HTML为:

<a href="#" class="button" data-product_id="18542" data-wp_nonce="7c3d595f98" id="fybAddCartEvent">
Add to cart</a>

还有剧本:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
from HTMLTestRunner import HTMLTestRunner
class Fotball_add_to_cart(unittest.TestCase):
    @classmethod
def setUpClass(inst):
    inst.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
    driver = inst.driver
    driver.get("http://ak:akpass@uat.athleticknit.com/football/")
    inst.driver.maximize_window()
    time.sleep(5)
    #click on "View All Fotball Products"
def test_click_on_view_all_fotball_products(self):
    viewProductsXpath = "a.woocommerce-nested-category-layout-see-more"
    self.viewProductsElement = self.driver.find_element_by_css_selector(viewProductsXpath)
    self.viewProductsElement.click()                                                      
    time.sleep(7)
    #select a product
def test_select_a_product_and_view_details(self):
    #select product
    tshirtXpath = "//a[@href="http://uat.athleticknit.com/product/f810/F810-000/"]"
    self.tshirtElement = self.driver.find_element_by_xpath(tshirtXpath)
    self.tshirtElement.click()
    time.sleep(60)
def test_press_add_to_cart(self):
    #press add to cart
    driver = self.driver
    addToCartXpath = '//*[@id="fybAddCartEvent"]'
    self.addToCartElement =WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(addToCartXpath))
    self.addToCartElement.click()
    time.sleep(5)
@classmethod    
def tearDownClass(inst):
    inst.driver.stop_client()
    inst.driver.close()
    inst.driver.quit()

实际上你在这里使用了显式等待

self.addToCartElement =WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(addToCartXpath))

因此,它会等待您的条件直到 20 秒,如果条件不满足,则显示TimeoutException.

如果您需要等待"添加到购物车",请尝试以下方式 -

element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.xpath, addToCartXpath)))

注意 :- 如果您有元素 ID,请按 ID 而不是 xpath 查找元素

 element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "fybAddCartEvent")))
 element.click()