Java 如何使用 Selenium WebDriver 选择 div id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21423547/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:39:20  来源:igfitidea点击:

How can I select the div id using Selenium WebDriver?

javajquery-uiseleniumselenium-webdriverwebdriver

提问by testing

Working with Selenium WebDriverand using Java. Is there any way to select the div id instead of select id in Selenium WebDriver?

使用Selenium WebDriver并使用Java。有没有办法在Selenium WebDriver中选择div id而不是select id?

I am using this HTML:

我正在使用这个 HTML:

<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" style="position: absolute; top: 410.8px; left: 998.9px; z-index: 1; display: block;">

回答by Algiz

You can found documentation (with java example) on http://docs.seleniumhq.org/docs/.

您可以在http://docs.seleniumhq.org/docs/上找到文档(带有 java 示例)。

In particular, the methlod you are looking for is

特别是,您正在寻找的方法是

WebDriver.findElement(By)

Sample code is

示例代码是

WebDriver driver = new xxxDriver();
driver.get(" ... ");
WebElement element = driver.findElement(By.id("ui-datepicker-div"));
element. ... // do whatever you want with the DIV block

回答by Husam

In webdriver, you can locate elements using various ways, like xpath, css, id or class of element. Your element can be identified in any of the following ways:

在 webdriver 中,您可以使用多种方式定位元素,例如 xpath、css、id 或元素类。您的元素可以通过以下任何一种方式进行识别:

driver.findElement(By.id("ui-datepicker-div")); //by id
driver.findElement(By.xpath("//div[@id='ui-datepicker-div']")); //by xpath
driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-div')]")); //another xpath

So on and so forth. The point is these locator will work on html elements, irrespective of what they are (select, div, input etc.).

等等等等。关键是这些定位器将适用于 html 元素,而不管它们是什么(选择、div、输入等)。