Java 如何在 selenium 中点击 web 元素的特定位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40546546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to click on a specific position of a web element in selenium?
提问by user2649233
I am working on video player automation. I am having difficulties in clicking at the end of the video player progress bar.
Consider an example of youtube video.
with the help of xpath i was able to find out the element of video progress bar. Now i wanted to click at the end of the video.
我正在研究视频播放器自动化。我在点击视频播放器进度条的末尾时遇到困难。
考虑一个 youtube 视频的例子。在 xpath 的帮助下,我能够找出视频进度条的元素。现在我想点击视频的结尾。
i tried using moveToElement(ele, xOffset, yOffset). But i can not have static offset here as the video player size depends on the browser window size. I tried to get the size of web element and use it as xoffset but that did not seem to be working. moveToElement(ele, ele.getRect().getWidth()-10, yOffset). Any suggestions here on how to achieve this?
我尝试使用moveToElement(ele, xOffset, yOffset)。但是我在这里不能有静态偏移,因为视频播放器的大小取决于浏览器窗口的大小。我试图获取 web 元素的大小并将其用作 xoffset 但这似乎不起作用。moveToElement(ele, ele.getRect().getWidth()-10, yOffset)。关于如何实现这一目标的任何建议?
采纳答案by Grasshopper
Try this code. I tried on Chrome 54 with webdriver 2.53 on windows 8. Do not touch the mouse during test or even better move the cursor out of screen range when test starts.
试试这个代码。我在 Windows 8 上使用 webdriver 2.53 在 Chrome 54 上尝试过。在测试期间不要触摸鼠标,或者最好在测试开始时将光标移出屏幕范围。
WebElement elem = driver.findElement(By.className("ytp-progress-bar"));
int width = elem.getSize().getWidth();
Actions act = new Actions(driver);
act.moveToElement(elem).moveByOffset((width/2)-2, 0).click().perform();
You can figure out the offset from the many attributes in the div 'ytp-progress-bar'. You do not need to find width etc.
您可以从 div 'ytp-progress-bar' 中的许多属性中计算出偏移量。您不需要查找宽度等。
You have to move to the progress bar initially because it disappears after 2-3 secs due to inactivity on the video screen.
您必须首先移至进度条,因为它会在 2-3 秒后由于视频屏幕上的不活动而消失。
回答by Dlyx
Sometimes Selenium is not enough and you need to work with Javascript and JQuery. I am not a Java developer but the code in C# would look like:
有时 Selenium 是不够的,您需要使用 Javascript 和 JQuery。我不是 Java 开发人员,但 C# 中的代码如下所示:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("Your Script");
There will be more help with JQuery. I hope I was able to help you.
JQuery 会有更多帮助。我希望我能帮到你。
回答by Grasshopper
To get the exact location to click on a page, there is a free firefox add-on that can help you achieve this accuracy. It is called 'MeasureIt'. With this, you can measure the exact vertical and horizontal distances you want to click
要获得点击页面的确切位置,有一个免费的 Firefox 插件可以帮助您实现这种准确性。它被称为“MeasureIt”。有了这个,您可以测量要单击的确切垂直和水平距离