Source:How can we pass a variable( string) to an xpath contains function?
String file = ...
Path path = Paths.get(file);
String content = Files.readString(path);
// Or readString(path, someCharset), if you need a Charset different from UTF-8
Best Selenium code snippet using org.openqa.selenium.By.ByXPath
Source:InstaGrow.java
...58 var pass= browser.findElement(new By.ByName("password"));59 pass.sendKeys(password);60 pass.sendKeys(Keys.RETURN);61 Wait.waitASecond();62 browser.findElement(new By.ByXPath(Xpaths.xpaths.get("not_now"))).click();63 Wait.waitASecond();64 browser.findElement(new By.ByXPath(Xpaths.xpaths.get("not_now2"))).click();65 Wait.waitASecond();66 log(String.format("ÐалогинилиÑÑ, как %s", login));67 // ÑиÑаем Ð±Ð°Ð·Ñ Ñегов68 try {69 TagsBase tag = new TagsBase();70 tagBase = tag.getTagBase();71 //System.out.println(tagBase);72 } catch (IOException e) {73 e.printStackTrace();74 }75 // Prepared to GROW _______________________________________________________76 //ÐÑбиÑаем акÑивноÑÑÑ77 int actionCase = 1; // вÑÐ±Ð¾Ñ Ð°ÐºÑивноÑÑи78 switch (actionCase) {79 case 1:80 randTag = tagBase.get(ThreadLocalRandom.current().nextInt(0, tagBase.size()));81 //System.out.println(randTag);82 var search=browser.findElement(new By.ByXPath(Xpaths.xpaths.get("search")));83 HandEnter.HandFieldEnter(search,randTag);84// for (int i = 0; i < randTag.length(); i++) {85// char letter = randTag.charAt(i);86//87// search.sendKeys(String.valueOf(letter));88// waitForKeys();89// }90 search.sendKeys(Keys.ENTER);91 search.sendKeys(Keys.ENTER);92 Wait.waitASecond();93 Wait.waitASecond();94 browser.findElement(new By.ByXPath(Xpaths.xpaths.get("first_pic"))).click();95 Wait.waitASecond();96 // var likeButton1 = browser.findElement(new By.ByXPath(Xpaths.xpaths.get("heart")));97 // System.out.println("attribute"+likeButton1.getAttribute("fill"));98 browser.findElement(new By.ByXPath(Xpaths.xpaths.get("like_button"))).click(); //ÐÐÐÐÐÐТ ÐÐÐÐ !!!99// System.out.println(browser.findElement(new By.ByXPath(xpaths.get("like_button"))).getAttribute("fill"));100// try {101// browser.findElement(new By.ByClassName("glyphsSpriteHeart__filled__24__red_5"));102// log("ТÑÑ Ð»Ð°Ð¹Ðº Ñже ÑÑоиÑ!");103// }104// catch (NoSuchElementException ex) {105// likeButton.click();106// log("ÐÐ°Ð¹ÐºÐ¾Ñ Ð¿Ð¾ÑÑавлен, мой генеÑал!");107// waitASecond();108// }109 //browser.findElement(new By.ByXPath(xpaths.get("account"))).getAttribute("href");110// browser2 = new ChromeDriver();111// browser2.get(browser.findElement(new By.ByXPath(xpaths.get("account"))).getAttribute("href")); browser2.findElement(new By.ByXPath(xpaths.get("head"))).getAttribute("rhpdm");112 // System.out.println(browser2.findElement(new By.ByXPath(xpaths.get("head"))).getAttribute("rhpdm"));113// Actions actions=new Actions(browser);114// actions.moveToElement(browser.findElement(new By.ByXPath(xpaths.get("search")))).sendKeys(Keys.ENTER);115// browser.findElement(new By.ByXPath(xpaths.get("search"))).sendKeys("b");116// waitForKeys();117// browser.findElement(new By.ByXPath(xpaths.get("search"))).sendKeys("c");118 break;119 }120 }121 /**122 * ÐаканÑиваем ÑабоÑÑ Ð±ÑаÑзеÑа.123 */124 private void end() {125 browser.close();126 log("Bye!");127 }128 /**129 * ÐдÑм ÑекÑндÑ. Ðа Ñамом деле Ð¾Ñ ÑÑÑÑ
до пÑÑи, ÑлÑÑайнÑм обÑазом.130 */131// public void waitASecond() {...
Source:StudyRaters.java
...32 33 @FindBy(how = How.XPATH, using = "//div[@class='slide-panel-header']//*[@title='Refresh']")34 public WebElement RefreshButton;35 //36 public By scheduled = new By.ByXPath("//img[@title='Scheduled']");37 public By completed = new By.ByXPath("//img[@title='Completed']");38 public By edited = new By.ByXPath("//img[@title='Editing']");39 public By rater = new By.ByXPath("//label[text()='Rater']");40 private List<Rater> table;41 private String ratersCount;42 public StudyRaters(WebDriver driver) {43 super(driver);44// if (ratersCount != "0"){45// setTable(readRatersFromWeb());46// }47// else{48// setTable(null);49// }50}51 52 public void sortBy(SortBy sortBy){53 Log.logInfo(String.format("Clicking on the %s to sort", sortBy.getValue()));54 switch (sortBy) {55 case RATER: UiHelper.click(rater);56 break;57 case SCHEDULED : UiHelper.click(scheduled);58 break;59 case COMPLETED: UiHelper.click(completed);60 break;61 case EDITED: UiHelper.click(edited);62 break;63 } 64 }65 66 public List<String> getDataAfterSotring(SortBy byName) {67 List<String> data = new ArrayList<String>();68 Log.logInfo(String.format("Clicking on the %s to sort", byName));69 switch (byName) {70 case RATER:71 data = TextHelper.getElementTextContent(UiHelper72 .findElements(new By.ByXPath(tableLocator + "[1]")));73 break;74 case SCHEDULED:75 data = TextHelper.getElementTextContent(UiHelper76 .findElements(new By.ByXPath(tableLocator + "[2]")));77 break;78 case COMPLETED:79 data = TextHelper.getElementTextContent(UiHelper80 .findElements(new By.ByXPath(tableLocator + "[3]")));81 break;82 case EDITED:83 data = TextHelper.getElementTextContent(UiHelper84 .findElements(new By.ByXPath(tableLocator + "[4]")));85 break;86 }87 return data;88 }89 90 public void closeRaters(){91 Log.logInfo("Closing Raters");92 UiHelper.click(CloseButton);93 //UiHelper.checkPendingRequests(Browser.getDriver());94 }95 96 97 public String getRatersCount(){98 ratersCount =99 TextHelper.splitParentheses(UiHelper.getText(new By.ByXPath("//h1[starts-with(text(),'Raters')]")));100 return ratersCount;101 }102 private List<Rater> readRatersFromWeb(){103 List<Rater> table = new ArrayList<Rater>();104 List<WebElement> elements = UiHelper.findElements(new By.ByXPath(tableLocator));105 List<String> textFromElements = TextHelper.getElementTextContent(elements);106 107 for (int i = 0; i<textFromElements.size();i=i+4){108 table.add(new Rater(textFromElements.get(i), textFromElements.get(i+1), textFromElements.get(i+2), textFromElements.get(i+3)));109 }110 return table;111 }112 113 114 public RaterDetails openRaterDetails(String raterName){115 Log.logInfo("Opening details of "+raterName);116 UiHelper.click(new By.ByXPath("//label[text()='"+raterName+"']"));117 return PageFactory.initElements(Browser.getDriver(), RaterDetails.class);118 }119 public List<Rater> getListOfRaterObjects() {120 setTable(readRatersFromWeb());121 return table;122 }123 public void setTable(List<Rater> table) {124 this.table = table;125 }126 /*-------------------------------NZ team-----------------------------------------------*/127 @FindBy(css=".sliding-container.raters-panel.ng-isolate-scope.opened")128 private WebElement panel;129 public boolean isRaterPanelOpened() {130 Log.logInfo("Verification if Raters Panel is opened.");...
Source:SogouV2WeixinService.java
...31 List<String> list = new ArrayList<>();32 try {33 driver.manage().deleteAllCookies();34 driver.get(firstUrl);35 By.ByXPath toolShowBy = new By.ByXPath("//a[@uigs='select_show']");36 WebElement toolShowElement = driver.findElement(toolShowBy);37 toolShowElement.click();38 By.ByXPath BtnTimeBy = new By.ByXPath("//a[@class='btn-time']");39 List<WebElement> btnElement = driver.findElements(BtnTimeBy);40 btnElement.get(0).click();41 By.ByXPath selecTimeBy = new By.ByXPath("//a[@uigs='select_time_day']");42 WebElement selectTimeElement = driver.findElement(selecTimeBy);43 selectTimeElement.click();44 btnElement = driver.findElements(BtnTimeBy);45 btnElement.get(2).click();46 Thread.sleep(3000);47 By.ByXPath searchInputBy = new By.ByXPath("//input[@placeholder='è¾å
¥å
¬ä¼å·æ微信å·']");48 WebElement searchInputElement = driver.findElement(searchInputBy);49 searchInputElement.sendKeys(weixinId);50 By.ByXPath searchEnterBy = new By.ByXPath("//a[@uigs='select_search_yes']");51 WebElement searchEnterElement = driver.findElement(searchEnterBy);52 searchEnterElement.click();53 Thread.sleep(3000);54 for(int i=0;i<10;i++) {55 try {56 By.ByXPath articleEnterBy = new By.ByXPath(String.format("//a[@uigs='article_title_%s']",String.valueOf(i)));57 WebElement articleEnterElement = driver.findElement(articleEnterBy);58 articleEnterElement.click();59 Thread.sleep(3000);60 }catch (Exception e) {61 logger.error(String.format("get article url error"),e);62 break;63 }64 }65 String handle = driver.getWindowHandle();66 for (String handles : driver.getWindowHandles()) {67 if (handles.equals(handle))68 continue;69 driver.switchTo().window(handles);70 list.add(driver.getCurrentUrl());...
Source:Leave.java
...3import org.openqa.selenium.Keys;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6public class Leave extends BasePage {7 private By btnLeave = new By.ByXPath("//*[@id=\"menu_leave_viewLeaveModule\"]");8 private By btnAssignLeave = new By.ByXPath("//*[@id=\"menu_leave_assignLeave\"]");9 private By btnApplyLeave = new By.ByXPath("//*[@id=\"menu_leave_applyLeave\"]");10 private By fieldEmployeeName = new By.ByXPath("//*[@id=\"assignleave_txtEmployee_empName\"]");11 private By selectAssignLeaveType = new By.ByXPath("//*[@id=\"assignleave_txtLeaveType\"]");12 private By fromDateAssignleave = new By.ByXPath("//*[@id=\"assignleave_txtFromDate\"]");13 private By toDateAssignLeave = new By.ByXPath("//*[@id=\"applyleave_txtToDate\"]");14 private By fromDateApplyleave = new By.ByXPath("//*[@id=\"applyleave_txtFromDate\"]");15 private By toDateApplyLeave = new By.ByXPath("//*[@id=\"applyleave_txtToDate\"]");16 private By btnAssignleave = new By.ByXPath("//*[@id=\"assignBtn\"]");17 private By menuLeaveList = new By.ByXPath("//*[@id=\"menu_leave_viewLeaveList\"]");18 private By toDateLabelAssign = new By.ByXPath("//*[@id=\"frmLeaveApply\"]/fieldset/ol/li[5]/label");19 private By toDateLabelApply = new By.ByXPath("//*[@id=\"frmLeaveApply\"]/fieldset/ol/li[4]/label");20 private By btnSubmitApply = new By.ByXPath("//*[@id=\"applyBtn\"]");21 private By menuApplyLeave = new By.ByXPath("//*[@id=\"menu_leave_applyLeave\"]");22 private By selectApplyLeaveType = new By.ByXPath("//*[@id=\"applyleave_txtLeaveType\"]");23 public Leave(WebDriver driver) { super(driver); }24 public void clickMenuLeave() throws InterruptedException {25 clickButton(btnLeave);26 }27 public void clickApplyLeave() throws InterruptedException {28 clickButton(menuApplyLeave);29 }30 public void clickAssignLeave() throws InterruptedException {31 clickButton(btnAssignLeave);32 }33 public void inputEmployeeName(String employeeName) throws InterruptedException {34 inputText(fieldEmployeeName, employeeName);35 }36 public void setSelectAssignLeaveType(String leaveType) throws InterruptedException {...
Source:performance.java
...3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import java.util.concurrent.TimeUnit;6import org.openqa.selenium.By;7import org.openqa.selenium.By.ByXPath;8import org.openqa.selenium.Keys;9import org.openqa.selenium.firefox.FirefoxDriver;10import org.openqa.selenium.support.ui.ExpectedConditions;11import org.openqa.selenium.support.ui.WebDriverWait;1213public class performance {14 // CONVERT PERCENTAGE TO GRADE15 private static String percentageToGrade(String val) {16 String newchar = val.replaceAll("%", "");17 int per = Integer.parseInt(newchar);18 if(per>89){19 return ("Grade A");20 }21 else if(per<90 && per>79) {22 return("Grade B");23 }24 else if(per>69 && per<80) {25 return ("Grade C");26 }27 else if(per>59 && per<70) {28 return ("Grade D");29 }30 else if(per>49 && per<60) {31 return ("Grade E");32 }33 else {34 return("Worst site");35 }36 }37 //CONVERT GRADE TO PERCENTAGE38 private static String GradeToPercentage(char val) {39 if(val =='A') {40 return ("90% - 100%");41 }42 else if(val == 'B') {43 return ("80% - 90%");44 }45 else if(val == 'C') {46 return ("70% - 80%");47 }48 else if(val == 'D') {49 return ("60% - 70%");50 }51 else if(val == 'E') {52 return ("50% - 60%");53 }54 else {55 return ("Worst Site");56 }57 }585960 public static void main(String[] args) throws InterruptedException {61 System.setProperty("webdriver.gecko.driver","C:\\\\geckodriver\\\\geckodriver.exe");62 WebDriver driver = new FirefoxDriver();63 driver.get("https://gtmetrix.com/");64 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;65 driver.findElement(new By.ByXPath("//input[@type='url']")).sendKeys("https://www.tothenew.com/",Keys.ENTER);66 WebDriverWait wait = new WebDriverWait(driver,30);67 WebElement Grade = wait.until(ExpectedConditions.visibilityOfElementLocated(new By.ByXPath("(//span[@class='report-score-percent'])[1]")));68 String grade1 = Grade.getText();69 String grade2 = driver.findElement(new By.ByXPath("(//span[@class='report-score-percent'])[2]")).getText();70 WebElement Grade0 = driver.findElement(new By.ByXPath("//div[@class='report-score report-score-grade-gtmetrix']/i"));71 String classname = Grade0.getAttribute("class");72 String[] arr =classname.split("-");73 String charracter = arr[2];74 char value = charracter.charAt(0);75 String Performance = percentageToGrade(grade1);76 String Structure= percentageToGrade(grade2);77 String Overall = GradeToPercentage(value);78 79 System.out.println("Overall Percentage Range is Between : "+Overall);80 System.out.println("PERFORMANCE GRADE IS : "+Performance);81 System.out.println("STRUCTURE GRADE IS : "+Structure);82 83 }84
...
Source:CatVideosTest.java
...32 }33 @Test34 void mustLog10YoutubeCatVideosUploadedToday() throws InterruptedException {35 Thread.sleep(3000);36 var searchButton = chromeDriver.findElement(By.ByXPath.className("ResponsiveHeaderTab__tab___2Um0g"));37 searchButton.click();38 var searchField = chromeDriver.findElement(By.ByXPath.id("search"));39 searchField.sendKeys("cats");40 searchField.sendKeys(Keys.ENTER);41 Thread.sleep(1000);42 var radioButtons = chromeDriver.findElements(By.ByXPath.className("RadioButton__inputButtonLabel___3oA7Q"));43 Thread.sleep(1000);44 for (WebElement button : radioButtons) {45 System.out.println(button.getText());46 if (button.getText().contains("Today")){47 button.click();48 break;49 }50 }51 Thread.sleep(1000);52 var catVideos = chromeDriver.findElements(By.ByXPath.className("VideoSearchCard__videoImageWrapper___zPMT9"));53 List<String> links = new ArrayList<>();54 for (int i = 0; i < 10; i++) {55 Thread.sleep(1000);56 var link = catVideos.get(i).findElement(By.ByXPath.tagName("a"));57 links.add(link.getAttribute("href"));58 }59 for (String link: links) {60 logger.info(String.format("Link added with URL: %s", link));61 }62 }63}...
Source:MainPage.java
...10 super(driver);11 }12 private By title = new By.ByCssSelector("a.logotypeImg");13 private By basket = new By.ByCssSelector("a.headerCartBox");14 private By search = new By.ByXPath("//input[@id='j-search']");15 private By accountButton = new By.ByXPath("//span[contains(text(), 'ÐккаÑнÑ')]");16 private By accountButton2 = new By.ByXPath("//button[@class='styles_userToolsToggler__imcSl']");17 private By loginButton = new By.ByXPath("//button[@class='userToolsBtn']");18 private By actualEmail = new By.ByXPath("//span[@class='userToolsSubtitle']");19 @Override20 public boolean isOpened() {21 return driver.findElement(title).isDisplayed();22 }23 public void open() {24 driver.get("https://www.21vek.by/");25 }26 public BasketPage openBasket() {27 driver.findElement(basket).click();28 return new BasketPage(driver);29 }30 public GoodPage searchGood() {31 WebElement searchBox = driver.findElement(search);32 searchBox.click();...
Source:FirstTest.java
...22 @Test23 public void Ssylka() //Don't work24 {25 driver.get("https://www.avito.ru/");26 driver.findElement(new By.ByXPath("/html/body/div[1]/div[2]/div/div[2]/div/div[2]/div/div/div/label[1]")).sendKeys("iPhone");27 driver.findElement(new By.ByXPath("//*[@id=\"app\"]/div[2]/div/div[2]/div/div[3]/button")).click();28 //WebElement myDynamicElement = (new WebDriverWait(driver, 100)).until(ExpectedConditions.presenceOfElementLocated(new By.ByXPath("//*[@id=\"app\"]/div[2]/div/div[2]/div/div[3]/button")));29 }30}...
By.ByXPath
Using AI Code Generation
1package org.openqa.selenium;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6public class ByXPath {7public static void main(String[] args) {8System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver_win32\\chromedriver.exe");9WebDriver driver = new ChromeDriver();10driver.manage().window().maximize();11email.sendKeys("
By.ByXPath
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.By;3By.cssSelector("#input-1");4import org.openqa.selenium.By;5By.className("form-control");6import org.openqa.selenium.By;7By.tagName("input");8import org.openqa.selenium.By;9By.id("input-1");10import org.openqa.selenium.By;11By.name("input-1");12import org.openqa.selenium.By;13By.linkText("Click here to visit Google");14import org.openqa.selenium.By;15By.partialLinkText("Visit Google");16import org.openqa.selenium.By;17import org.openqa.selenium.By;18By.cssSelector("#input-1");19import org.openqa.selenium.By;20By.className("form-control");21import org.openqa.selenium.By;22By.tagName("input");23import org.openqa.selenium.By;24By.id("input-1");25import org.openqa.selenium.By;26By.name("input-1");27import org.openqa.selenium.By;28By.linkText("Click here to visit Google");29import org.openqa.selenium.By;30By.partialLinkText("Visit Google");31import org.openqa.selenium.By;32import org.openqa.selenium.By;33By.cssSelector("#input
By.ByXPath
Using AI Code Generation
1By xpath = By.xpath("xpath of the element");2WebElement element = driver.findElement(xpath);3element.click();4By xpath = By.xpath("xpath of the element");5WebElement element = driver.findElement(xpath);6element.click();7By.ByXPath xpath = new By.ByXPath("xpath of the element");8WebElement element = driver.findElement(xpath);9element.click();10By.ByXPath xpath = new By.ByXPath("xpath of the element");11WebElement element = driver.findElement(xpath);12element.click();13By.ByXPath xpath = new By.ByXPath("xpath of the element");14WebElement element = driver.findElement(xpath);15element.click();16By.ByXPath xpath = new By.ByXPath("xpath of the element");17WebElement element = driver.findElement(xpath);18element.click();19By xpath = By.xpath("xpath of the element");20WebElement element = driver.findElement(xpath);21element.click();
1String file = ...2Path path = Paths.get(file);3String content = Files.readString(path);4// Or readString(path, someCharset), if you need a Charset different from UTF-85
1public static String readFileAsString(String filePath) throws IOException {2 DataInputStream dis = new DataInputStream(new FileInputStream(filePath));3 try {4 long len = new File(filePath).length();5 if (len > Integer.MAX_VALUE) throw new IOException("File "+filePath+" too large, was "+len+" bytes.");6 byte[] bytes = new byte[(int) len];7 dis.readFully(bytes);8 return new String(bytes, "UTF-8");9 } finally {10 dis.close();11 }12}13
1String content = new String(Files.readAllBytes(Paths.get(filename)), "UTF-8");2
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!