有时我可以单击按钮,有时不起作用

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

如果在页面上找到元素,我试图单击按钮。大部分时间该元素都在页面上。 3次有效,1次无效。这是我的代码:

elements = driver.find_elements_by_xpath("//h2[contains(text(),'No results found')]")
if (len(elements)>0):
    WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CLASS_NAME, 'ut-navigation-button-control'))).click()
else:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'Buy Now')]"))).click()

下面是我有时收到的错误:

ElementClickInterceptedException: Message: Element <button class="ut-navigation-button-control"> is not clickable at point (128,80) because another element <div class="ut-click-shield showing interaction"> obscures it
    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'Buy Now')]"))).click()
    except:
        WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CLASS_NAME, 'ut-navigation-button-control'))).click()

它是这样工作的,但是在例外期间要花很多时间。有人知道如何使它快速通过吗?

python selenium selenium-webdriver webdriver webdriverwait
2个回答
0
投票

您可以在元素上执行JavaScriptExecutor单击,因为它直接在div上执行操作,不受元素在页面上的位置的影响。您可以这样做:

button = driver.find_element_by_xpath("//button[contains(text(),'Back')]")
driver.execute_script("arguments[0].click();", button)

0
投票

文本为未找到结果的元素仅在搜索失败后才会出现。成功搜索后,要单击所需的元素,必须为element_to_be_clickable()引入WebDriverWait,然后可以使用以下基于Locator Strategies

try:
    # wait for the visibility of the element with text as "No results found"
    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()='No results found']")))
    # if the element with text as No results found, induce WebDriverWait for invisibilityOfElement obscuring the clickable element
    new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("//div[@class='ut-click-shield showing interaction']")));
    # once the invisibilityOfElement obscuring the clickable element is achieved, click on the desired element inducing WebDriverWait
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='ut-navigation-button-control']"))).click()
except TimeoutException:
    # if search for the element with text as "No results found" raises "TimeoutException" exception click on the element with text as "Buy Now" inducing WebDriverWait
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(,. 'Buy Now')]"))).click()
© www.soinside.com 2019 - 2024. All rights reserved.