Selenium 和 Python:单击具有 "data-disable-with" 属性的按钮时出现问题

Selenium and Python: Trouble with clicking a button with "data-disable-with" attribute

[编辑:在下方添加了 Chrome 开发人员视图的屏幕截图...]

我正在尝试点击这个对象:

<input type="submit" name="commit" value="Load Report" class="button" data-disable-with="Load Report">

在 UI 中,该按钮是可单击的,直到它被单击以启动报告。然后它会被禁用,直到报告加载。

但是当我在代码中调用时:

driver.find_element_by_name("commit").click()

它抛出一个异常:

ElementNotVisibleException: element not interactable
  (Session info: chrome=71.0.3578.98)
  (Driver info: chromedriver=2.45.615355 (d5698f682d8b2742017df6c81e0bd8e6a3063189),platform=Mac OS X 10.14.0 x86_64)

所以,我很确定我找到了正确的按钮(除非有另一个名为 "commit" 的按钮),但由于某种原因它不可点击。它前面没有可辨别的物体,但也许在 CSS 或...中隐藏着什么?我是个什么都不懂的菜鸟。有什么提示吗?

您可以使用显式等待元素可见

 System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
 WebDriver driver = new ChromeDriver();
 driver.get("URL");
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.manage().window().maximize();
 WebElement commitBtn = driver.findElement(By.name("commit"));
 WebDriverWait wait = new WebDriverWait(driver, 20);
 wait.until(ExpectedConditions.visibilityOf(commitBtn));
 commitBtn.click();

或者你可以使用javascriptexecutor

WebElement commitBtn = driver.findElement(By.name("commit"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(commitBtn));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", commitBtn );

所需的元素是一个 dynamic 元素,因此要在该元素上调用 click(),您需要为元素可点击,您可以使用以下任一解决方案:

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.button[name='commit'][value='Load Report']"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='button' and @name='commit'][@value='Load Report']"))).click()
    
  • 注意:您必须添加以下导入:

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