首页 > 解决方案 > Python:元素不是可点击的硒

问题描述

我正在尝试用 Python 编写一个程序,该程序单击到下一页,直到它到达最后一页。我在 Stackoverflow 上关注了一些旧帖子并编写了以下代码:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException


driver = webdriver.Chrome(executable_path="/Users/yasirmuhammad/Downloads/chromedriver")
driver.get("https://stackoverflow.com/users/37181/alex-gaynor?tab=tags")



while True:
    try:
        driver.find_element_by_link_text('next').click()

    except NoSuchElementException:
        break

但是,当我运行该程序时,它会引发以下错误:

selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a href="/users/37181/alex-gaynor?tab=tags&amp;sort=votes&amp;page=3" rel="next" title="go to page 3">...</a> is not clickable at point (1180, 566). Other element would receive the click: <html class="">...</html>
  (Session info: chrome=68.0.3440.106)

我还关注了 Stackoverflow 的一个线程(selenium exception: Element is not clickable at point),但没有运气。

标签: pythonpython-3.xseleniumselenium-webdriverwebdriver

解决方案


根据您的问题单击下一页直到到达最后一页,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    from selenium.common.exceptions import NoSuchElementException
    from selenium.common.exceptions import StaleElementReferenceException
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://stackoverflow.com/users/37181/alex-gaynor?tab=tags")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='grid--cell fc-white js-notice-close' and @aria-label='notice-dismiss']"))).click()
    while True:
        try:
        driver.execute_script(("window.scrollTo(0, document.body.scrollHeight)"))
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='pager fr']//a[last()]/span[@class='page-numbers next']")))
        driver.find_element_by_xpath("//div[@class='pager fr']//a[last()]/span[@class='page-numbers next']").click()
        except (TimeoutException, NoSuchElementException, StaleElementReferenceException) :
        print("Last page reached")
        break
    driver.quit()
    
  • 控制台输出:

    Last page reached
    

推荐阅读