Python3 Ubuntu 脚本上的 Selenium 在无头时可见失败时工作

Python3 Selenium on Ubuntu script works when visible fails when headless

我在 Ubuntu 运行 上有一个 python3 selenium 脚本,当我尝试 运行 无头时,它在 chrome 中成功元素不可交互时出错:

Traceback (most recent call last):
  File "file.py", line 143, in <module>
    driver.find_element_by_xpath('//*[@id="ctl00_MainContent_MyReportViewer_ctl04_ctl00"]').click()                  
  File "/home/jobs/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click                      
    self._execute(Command.CLICK_ELEMENT)
  File "/home/jobs/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute                      
    return self._parent.execute(command, params)
  File "/home/jobs/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute                      
    self.error_handler.check_response(response)
  File "/home/jobs/.local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response                      
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable                      
  (Session info: headless chrome=87.0.4280.88

我看到 post 可能是 chrome 与对象交互的方式不同,所以我在 Firefox 上也尝试过,结果相同。

我要更改的唯一行是:

chrome_options.add_argument("--headless")

这个错误信息...

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

...表示当您调用单击它时所需的 不可交互。

该元素似乎是一个动态元素,所以点击该元素需要诱导WebDriverWait for the element_to_be_clickable() and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ctl00_MainContent_MyReportViewer_ctl04_ctl00"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id="ctl00_MainContent_MyReportViewer_ctl04_ctl00"]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

更新

如果您仍然无法点击该元素,您可以使用 ActionChains,如下所示:

  • 使用CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ctl00_MainContent_MyReportViewer_ctl04_ctl00")))
    ActionChains(driver).move_to_element(element).click(element).perform()
    
  • 使用XPATH:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id="ctl00_MainContent_MyReportViewer_ctl04_ctl00"]")))
    ActionChains(driver).move_to_element(element).click(element).perform()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.action_chains import ActionChains