【问题标题】:Selenium and Python: Trouble with clicking a button with "data-disable-with" attributeSelenium 和 Python:单击具有“data-disable-with”属性的按钮时遇到问题
【发布时间】:2018-12-26 13:31:52
【问题描述】:

[编辑:在下方添加了 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 中或...?我是个一无所知的菜鸟。有什么提示吗?

【问题讨论】:

  • @PedroLobito 如果元素在不同的框架中,它会抛出一个ElementNotFoundException
  • 你试过添加等待点击吗?可能在加载报告或需要完成某些其他操作之前单击该元素。另一种可能性是INPUT 元素永远不会变得可见,您需要找到要与之交互的可见元素。没有页面链接很难说
  • @JeffC 感谢您的 cmets。可悲的是,这是一个被密码锁定的金融系统,所以我无法分享。我将不得不尝试联系开发人员。

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

所需元素是 动态 元素,因此要在元素上调用 click(),您需要诱导 WebDriverWait 以使 元素可点击 并且您可以使用以下任一解决方案:

  • 使用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
    

【讨论】:

  • 请查看我现在针对您的问题发布的答案。 :not(style) 没有(或不应该)做你认为它做的事情(或它实际做的事情)。
  • 谢谢,我正在仔细检查您在答案中提供的每一个细节。
  • 所以 XPATH 和 CSS 方法都有效 - 谢谢!但是如果涉及到“等待”,为什么我不能暂停程序几秒钟,然后继续前进呢?我认为“等待”比这更微妙......
【解决方案2】:

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

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

【讨论】:

  • 谢谢。但这段代码都是javascript。我怎么能在python中做到这一点?我不明白什么?
  • 你也可以在 python 中找到类似的代码。因为我在这方面没有太多的专业知识。在 python 中,还有 JavascriptExecutor 接口。只是改变了一些语法
猜你喜欢
  • 2020-05-18
  • 2019-02-07
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多