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

时间:2019-12-25 13:50:09

标签: python selenium selenium-webdriver webdriver webdriverwait

如果在页面上找到一个元素,我试图单击一个按钮。大部分时间该元素都在页面上。 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()

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

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()