下面列出了怎么用org.openqa.selenium.By的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public SelenideElement deselectRow(By rowBy) {
this.shouldBe(VISIBLE)
.shouldBe(ENABLED);
SelenideElement row = getRow(rowBy)
.shouldBe(visible)
.shouldHave(selectedClass);
WebDriver webDriver = WebDriverRunner.getWebDriver();
Actions action = new Actions(webDriver);
Keys controlKey = getControlKey();
action.keyDown(controlKey)
.click(row.getWrappedElement())
.keyUp(controlKey)
.build()
.perform();
return row;
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts("foo")
public void onChange() throws Exception {
final String html
= "<html>\n"
+ "<head><title>foo</title></head>\n"
+ "<body>\n"
+ " <p>hello world</p>\n"
+ " <form name='form1'>\n"
+ " <textarea name='textarea1' onchange='alert(this.value)'></textarea>\n"
+ " <input name='myButton' type='button' onclick='document.form1.textarea1.value=\"from button\"'>\n"
+ " </form>\n"
+ "</body></html>";
final WebDriver driver = loadPage2(html);
final WebElement textarea = driver.findElement(By.name("textarea1"));
textarea.sendKeys("foo");
driver.findElement(By.name("myButton")).click();
verifyAlerts(driver, getExpectedAlerts());
}
/**
* @throws Exception if an error occurs
*/
@Test
@Alerts({"click check1Label", "click listItem1", "click list",
"click check1", "click listItem1", "click list", "false"})
public void triggerCheckboxCheckedFor() throws Exception {
final String html =
" <ul onclick='log(\"click list\")'>\n"
+ " <li onclick='log(\"click listItem1\")'>\n"
+ " <label id='check1Label' for='check1' onclick='log(\"click check1Label\")'>Checkbox 1</label>\n"
+ " <input id='check1' name='checks' value='1' type='checkbox' checked "
+ "onclick='log(\"click check1\");'>\n"
+ " </li>\n"
+ " </ul>\n"
+ " <button id='check' onclick='log(document.getElementById(\"check1\").checked)'>Check</button>\n";
final WebDriver driver = loadPage2(generatePage(html));
driver.findElement(By.id("check1Label")).click();
driver.findElement(By.id("check")).click();
assertTitle(driver, String.join(";", getExpectedAlerts()) + ";");
}
private void testSearchSelect() throws Exception {
waitAndClickByValue("CAT");
waitAndClickByXpath("//div[@data-label='Travel Account Type Code']/div/div/button[@class='btn btn-default uif-action icon-search']");
waitSearchAndReturnFromLightbox();
waitAndClickButtonByText(WebDriverLegacyITBase.SEARCH);
By[] bysPresent = new By[] {By.xpath("//a[contains(text(), 'a6')]"), By.xpath("//a[contains(text(), 'a9')]"), By.xpath("//a[contains(text(), 'a14')]")};
assertElementsPresentInResultPages(bysPresent);
waitAndClickByName(LOOKUP_RESULTS);
assertButtonEnabledByText(WebDriverLegacyITBase.RETURN_SELECTED_BUTTON_TEXT);
waitAndClickByName(LOOKUP_RESULTS);
assertButtonDisabledByText(WebDriverLegacyITBase.RETURN_SELECTED_BUTTON_TEXT);
assertMultiValueSelectAllThisPage();
assertMultiValueDeselectAllThisPage();
waitAndClickByName(LOOKUP_RESULTS);
waitAndClickButtonByText(WebDriverLegacyITBase.SEARCH);
checkForIncidentReport();
}
/**
* In this case, we have one book and one borrower,
* so we should get a dropdown
*
* more detail:
* Under lending, books and borrowers inputs have three modes.
* a) if no books/borrowers, lock the input
* b) If 1 - 9, show a dropdown
* c) If 10 and up, show an autocomplete
*/
@Test
public void test_shouldShowDropdowns() {
// clear the database...
driver.get("http://localhost:8080/demo/flyway");
ApiCalls.registerBook("some book");
ApiCalls.registerBorrowers("some borrower");
driver.get("http://localhost:8080/demo/library.html");
// using the arrow keys to select an element is a very "dropdown" kind of behavior.
driver.findElement(By.id("lend_book")).sendKeys(Keys.ARROW_UP);
driver.findElement(By.id("lend_borrower")).sendKeys(Keys.ARROW_UP);
driver.findElement(By.id("lend_book_submit")).click();
final String result = driver.findElement(By.id("result")).getText();
assertEquals("SUCCESS", result);
}
/**
* @throws Exception if an error occurs
*/
@Test
@Alerts("frame loaded")
@NotYetImplemented
public void framesetInsideForm() throws Exception {
final String html = "<html>\n"
+ "<form id='tester'>\n"
+ " <frameset>\n"
+ " <frame name='main' src='" + URL_SECOND + "' />\n"
+ " </frameset>\n"
+ "</form>\n"
+ "</html>";
final String html2 = "<html><body>\n"
+ "<script>\n"
+ " alert('frame loaded');\n"
+ "</script>\n"
+ "</body></html>";
getMockWebConnection().setResponse(URL_SECOND, html2);
final WebDriver webDriver = loadPageWithAlerts2(html);
assertEquals(1, webDriver.findElements(By.name("main")).size());
assertEquals(0, webDriver.findElements(By.id("tester")).size());
}
protected void testTravelCompanyCreateNewDocumentSequenceGeneration() throws Exception {
waitAndClickByLinkText("Create New");
createTravelCompanyDoc();
int travelCompanyIdDoc1 = Integer.parseInt(findElement(By.xpath(TRAVEL_CO_ID_XPATH)).getText());
navigate();
waitAndClickByLinkText("Create New");
createTravelCompanyDoc();
int travelCompanyIdDoc2 = Integer.parseInt(findElement(By.xpath(TRAVEL_CO_ID_XPATH)).getText());
assertTrue("The Travel Company Id on the second document should be one higher than the first document. "
+ "travelCompanyIdDoc1: " + travelCompanyIdDoc1 + ", travelCompanyIdDoc2: " + travelCompanyIdDoc2 ,
travelCompanyIdDoc2 == travelCompanyIdDoc1 + 1);
}
/**
* Called to login to the portal if necessary.
*/
protected static void login() {
driver.get(loginUrl);
List<WebElement> uels = driver.findElements(By.id(usernameId));
List<WebElement> pwels = driver.findElements(By.id(passwordId));
// If there is no login or password fields, don't need to login.
if (!uels.isEmpty() && !pwels.isEmpty()) {
System.out.println("login: found userid and password fields");
WebElement userEl = uels.get(0);
WebElement pwEl = pwels.get(0);
// perform login
userEl.clear();
userEl.sendKeys(username);
pwEl.clear();
pwEl.sendKeys(password);
pwEl.submit();
}
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = "[object HTMLUnknownElement]",
IE = "[object HTMLBGSoundElement]")
public void simpleScriptable() throws Exception {
final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_ + "<html><head>\n"
+ "<script>\n"
+ " function test() {\n"
+ " alert(document.getElementById('myId'));\n"
+ " }\n"
+ "</script>\n"
+ "</head><body onload='test()'>\n"
+ " <bgsound id='myId'/>\n"
+ "</body></html>";
final WebDriver driver = loadPageWithAlerts2(html);
if (driver instanceof HtmlUnitDriver && getExpectedAlerts()[0].contains("Sound")) {
assertTrue(HtmlBackgroundSound.class.isInstance(toHtmlElement(driver.findElement(By.id("myId")))));
}
}
public HashMap<String, String> getCellValue(WebElement Element, int tr,
int td) {
int rowCounter = 0;
int colCounter = 0;
String rowKey = null;
String colKey = null;
HashMap<String, String> HashTable = new HashMap<>();
String strObj = Data;
List<WebElement> tableList = Element.findElements(By
.cssSelector("div[class='" + strObj + "'] tr td"));
for (WebElement listIterator : tableList) {
String TagName = listIterator.getTagName();
if (TagName.equals("tr")) {
rowKey = "R" + rowCounter++;
}
if (TagName.equals("td")) {
colKey = "C" + colCounter++;
}
HashTable.put(rowKey + colKey, listIterator.getText());
}
return HashTable;
}
private void completeFillIdentifierSteps(String identifier) {
By switchAccountButtonBy = By.cssSelector("div[aria-label='Switch account']");
By useAnotherAccountButtonBy = By.xpath("//div[contains(text(), 'Use another account')]");
if (isElementPresent(switchAccountButtonBy)) {
click(switchAccountButtonBy);
waitForLoginPanelAnimationToComplete();
}
if (isElementPresent(useAnotherAccountButtonBy)) {
click(useAnotherAccountButtonBy);
waitForLoginPanelAnimationToComplete();
}
fillTextBox(identifierTextBox, identifier);
}
@Parameters({"searchWord", "items"})
@Test
public void searchProduct(String searchWord, int items) {
// find search box and enter search string
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys(searchWord);
WebElement searchButton =
driver.findElement(By.className("search-button"));
searchButton.click();
assertThat(driver.getTitle())
.isEqualTo("Search results for: '" + searchWord + "'");
List<WebElement> searchItems = driver
.findElements(By.xpath("//h2[@class='product-name']/a"));
assertThat(searchItems.size())
.isEqualTo(items);
}
public InstructorStudentListPage clickShowPhoto(String courseId, String studentName) {
String rowId = getStudentRowId(courseId, studentName);
WebElement photoCell = browser.driver.findElement(By.id("studentphoto-c" + rowId));
WebElement photoLink = photoCell.findElement(By.tagName("a"));
click(photoLink);
return this;
}
@Test
public void SauceDemo() {
browser.goTo("https://www.saucedemo.com/");
String email = "standard_user";
String password = "secret_sauce";
browser.element(By.id("user-name")).setText(email);
browser.element(By.id("password")).setText(password);
browser.element(By.className("btn_action")).click();
}
@Test
public void testBattlegroundCreation1() throws Exception {
SeleniumTestUtils.login(driver, codeDefendersHome, "codedefenders", "codedefenderspw");
driver.findElement(By.id("createBattleground")).click();
driver.findElement(By.id("maxAssertionsPerTest")).click();
driver.findElement(By.id("maxAssertionsPerTest")).clear();
driver.findElement(By.id("maxAssertionsPerTest")).sendKeys("3");
driver.findElement(By.xpath("(//button[@type='button'])[3]")).click();
driver.findElement(By.linkText("moderate")).click();
driver.findElement(By.id("createButton")).click();
checkNrOfGames();
}
public void editFeedbackResponseComment(String commentIdSuffix, String newCommentText) {
WebElement commentRow = waitForElementPresence(By.id("responseCommentRow" + commentIdSuffix));
click(commentRow.findElements(By.tagName("a")).get(1));
WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + commentIdSuffix));
fillRichTextEditor("responsecommenttext" + commentIdSuffix, newCommentText);
click(commentEditForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a")));
ThreadHelper.waitFor(1000);
}
@Override
public void run(RecordingSimulatorModule recordingSimulatorModule) {
String baseUrl = (String) opts.get(URL);
WebDriver driver = recordingSimulatorModule.getWebDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get(baseUrl + Pages.DYNAMIC_DEMO_PAGE);
driver.findElement(By.id(CREATE_DYNAMIC_ID)).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id(LATE_CREATION_ID)));
}
private String formatBy(By by) {
if (by instanceof Selectors.ByChain) {
return formatBy(((Selectors.ByChain) by).getLastBy());
}
if (by instanceof Selectors.ByCubaId) {
return ((Selectors.ByCubaId) by).getCubaId();
}
return by.toString();
}
@Test
public void webrtcTest(FirefoxDriver driver) {
driver.get(
"https://webrtc.github.io/samples/src/content/devices/input-output/");
assertThat(driver.findElement(By.id("video")).getTagName(),
equalTo("video"));
}
/**
* click on the found action
*
* @param action name of action
*/
public void clickOnFoundAction(String action) {
actionsFactory
.createAction(seleniumWebDriver)
.doubleClick(
waitWithRedrawTimeout.until(
ExpectedConditions.elementToBeClickable(
By.xpath(String.format(FOUND_ACTION_BY_NAME, action)))))
.perform();
}
@Test
public void findElementsTwoByEmptyChild() {
final AllDriver driver = mock(AllDriver.class);
final WebElement elem1 = mock(WebElement.class, "webElement1");
final WebElement elem2 = mock(AllElement.class, "webElement2");
final WebElement elem3 = mock(AllElement.class, "webElement3");
final WebElement elem4 = mock(AllElement.class, "webElement4");
final WebElement elem5 = mock(AllElement.class, "webElement5");
final List<WebElement> elems = new ArrayList<>();
final List<WebElement> elems12 = new ArrayList<>();
elems12.add(elem1);
elems12.add(elem2);
final List<WebElement> elems34 = new ArrayList<>();
elems34.add(elem3);
elems34.add(elem4);
final List<WebElement> elems5 = new ArrayList<>();
elems5.add(elem5);
final List<WebElement> elems345 = new ArrayList<>();
elems345.addAll(elems34);
elems345.addAll(elems5);
when(driver.findElements(By.name("cheese"))).thenReturn(elems12);
when(elem1.findElements(By.name("photo"))).thenReturn(elems);
when(elem2.findElements(By.name("photo"))).thenReturn(elems5);
ByChained by = new ByChained(By.name("cheese"), By.name("photo"));
assertThat(by.findElements(driver)).isEqualTo(elems5);
}
protected void actionSendKeysArrowDown(String id) {
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id(id)));
actions.click();
actions.sendKeys(Keys.ARROW_DOWN);
actions.build().perform();
}
private String returnInputValueForm2(int index) {
return driver
.findElement(By.xpath("//form[@id='"
+ AppHtmlElements.APP_CONFIG_FORM2
+ "']/table/tbody[1]/tr/[" + index + "]/td[2]/input"))
.getAttribute(ATTRIUBTE_VALUE);
}
public static void submitLoginForm(String username, String password) {
WebElement usernameInput = driver.findElement(By.name("j_username"));
usernameInput.clear();
usernameInput.sendKeys(username);
WebElement passwordInput = driver.findElement(By.name("j_password"));
passwordInput.clear();
passwordInput.sendKeys(password);
WebElement login = driver.findElement(By.name("submit"));
login.click();
}
@Test
@DisplayName("by(By) returns found element")
void byForByReturnsElement() {
WebElement webElement = mock(WebElement.class);
TestFragment mockElement = mock(TestFragment.class);
doReturn(webElement).when(searchContext).findElement(any(By.ById.class));
doReturn(mockElement).when(factory).createInstanceOf(descriptor(TestFragment.class, webElement));
TestFragment element = cut.by(id("someId"));
assertThat(element).isSameAs(mockElement);
}
@Test
public void filtering() {
open();
String status = findElement(By.id("status")).getText();
Assert.assertEquals("Event received", status);
}
/**
* Waits for a confirmation modal to appear and click the cancel button.
*/
public void waitForConfirmationModalAndClickCancel() {
waitForModalShown();
WebElement cancelButton = browser.driver.findElement(By.className("modal-btn-cancel"));
waitForElementToBeClickable(cancelButton);
clickDismissModalButtonAndWaitForModalHidden(cancelButton);
}
@Test
public void completionApply() throws InterruptedException {
driver.navigate().to(url);
// Start the add-in
driver.findElement(By.id("startButton")).click();
driver.findElement(By.id("genconfURI")).sendKeys(genconfURI);
driver.findElement(By.id("expression")).click();
driver.findElement(By.id("expression")).sendKeys("self.n");
Thread.sleep(2000);
driver.findElement(By.id("expression")).sendKeys("a");
Thread.sleep(1000);
assertEquals(
"[{\"documentation\":\"EAttribute named name in ENamedElement(http://www.eclipse.org/emf/2002/Ecore)\",\"cursorOffset\":9,\"label\":\"name\",\"type\":\"EAttribute\",\"value\":\"name\"}]",
driver.executeScript("return JSON.stringify(window.awesomplete._list)"));
assertEquals("Feature na not found in EClass EPackage (4, 7)",
driver.findElement(By.id("validationDiv")).getText());
assertEquals("null", driver.findElement(By.id("resultDiv")).getText());
driver.findElement(By.id("awesomplete_list_1_item_0")).click();
Thread.sleep(1000);
assertEquals("self.name", driver.findElement(By.id("expression")).getAttribute("value"));
assertEquals("", driver.findElement(By.id("validationDiv")).getText());
assertEquals("anydsl", driver.findElement(By.id("resultDiv")).getText());
}
protected BiFunction<WebElement, R, Boolean> deselect() {
return (selected, value) -> {
WebElement selection = selected.findElements(By.tagName("div")).get(0);
if (identity().apply(value).equals(selection.getText())) {
WebElement element = selected.findElement(By.xpath(".//a[contains(@class,'select2-search-choice-close')]"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
pause(500);
return true;
}
return false;
};
}
public void configureRp(String profile) {
fluentWait(ONE_SEC);
WebElement element = webDriver.findElement(By.className("checkbox1"));
element.click();
fluentWait(ONE_SEC);
WebElement link = waitElementByClass("RelyingPartyConfigLink");
link.click();
pickprofileAndSave(profile);
}