簡體   English   中英

有時我可以點擊按鈕,有時不起作用

[英]Sometime I can click on the button, sometime doesn't work

如果在頁面上找到元素,我會嘗試單擊按鈕。 該元素大部分時間都在頁面上。 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()

它是這樣工作的,但在除外期間需要很多時間。 有誰知道如何讓它快速通過,除了?

您可以對元素執行JavaScriptExecutor單擊,因為它直接在 div 上執行操作,不受元素在頁面上的位置的影響。
你可以這樣做:

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

文本為No results found的元素只會在搜索失敗后出現。 在成功搜索時,要單擊所需的元素,您必須為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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM