「Selenium」- 在页面中,点击按钮(或元素) @20210311

问题描述

该笔记将记录:在 Selenium 中,如何使用代码点击按钮,以及常见问题处理。

解决方案

使用 click() 点击

通常点击元素使用 click() 方法即可:

// 选择元素并进行点击
webDriver.findElement(By.id("buttoncheck")).click()

// 等待元素可以点击
 new WebDriverWait(webDriver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("xpath-query"))).click()

使用 JavaScript 点击

或者,当找到元素后,使用 JavaScript 点击:

((JavascriptExecutor) webDriver).executeScript("arguments[0].click();", button);

该方法可以我们遇到的解决如下问题:

org.openqa.selenium.ElementClickInterceptedException: element click intercepted:
 Element xxxxxxxx is not clickable at point (1154, 91). Other element would receive the click: xxxxxxx

更多点击动作

复杂的点击操作(长按、右键、双击),参考 Test Automation With Selenium Click Button Method(Examples) 页面

关于点击需要注意的事项

现实世界是复杂的,我们将在该部分中记录我们遇到的问题(与点击相关)。

# 10/03/2020 某些元素,当在浏览器窗口(viewport)中可见时,才会被绑定点击事件。因此,如果没有滚动到该元素使其可见,点击动作是无效的。在 Firefox 80.0.1 (64-bit) 中,滚动至元素可见,会发现在 Inspector 中该元素的后面后显示 event 标签。使用如下代码进行滚动及滚动完成的检查:

// 下面是与滚动至元素可见的代码的参考文献
// https://www.guru99.com/scroll-up-down-selenium-webdriver.html
// https://stackoverflow.com/questions/42982950/how-to-scroll-down-the-page-till-bottomend-page-in-the-selenium-webdriver

// 第一步、执行滚动
((JavascriptExecutor) webDriver).executeScript('arguments[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});', bodyElement);

// 理解 scrollIntoView 需要:
// 阅读:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
// 在我们的场景中,block: "end" 是关键设置,否则会出现“没有显示元素,而下面滚动已经提示完成”,导致事件没有绑定到元素上便触发点击事件。

// 等待滚动完成
new WebDriverWait(webDriver, 30).until(new Function<WebDriver, Boolean>() {
    @Override
    public Boolean apply(WebDriver tmpWebDriver) {
    	String isVisibleJavascript =  "return (arguments[0].getBoundingClientRect().top >= 0) && (arguments[0].getBoundingClientRect().bottom <= window.innerHeight);"
		Object pageReady = ((JavascriptExecutor) tmpWebDriver).executeScript(isVisibleJavascript, bodyElement);
		Boolean complete = pageReady.toString().equals("true");
		System.out.println("检查滚动是否完成:${complete}"); // Groovy
		return complete;
    }
});

// 要理解 等待滚动完成 代码,需要阅读以下文档(依序):
// https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling
// https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
// https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight

相关文章

「Selenium」- 文件上传

参考文献

Test Automation With Selenium Click Button Method(Examples)
Check if element is clickable in Selenium Java - Stack Overflow


posted @ 2021-03-11 16:21  研究林纳斯写的  阅读(715)  评论(0编辑  收藏  举报