I want to count elements in selenium.
When using xpath //*[#class='z-listbox-body']/table/tbody[2]/tr I get 3 matching nodes.
But my code gets 12 instead of 3:
public String countTable(){
List<WebElement> located_elements = driver.findElements(By.xpath("//*[#class='z-listbox-body']/table/tbody[2]/tr"));
int count = 0;
for(WebElement located_element:located_elements){
count ++;
}
String s = String.valueOf(count);
return s;
}
Please try to use below code:
public String countTable(WebDriver dirver){
List located_elements = driver.findElements(By.xpath("//[#class='z-listbox-body']/table/tbody[2]/tr"));
return String.valuseOf(located_elements.size());
}
Related
This is the website I am practicing on
https://rahulshettyacademy.com/dropdownsPractise/
This is my code:
WebElement origin = driver.findElement(By.xpath("//*[#id=\"ctl00_mainContent_ddl_originStation1\"]"));
Select ori = new Select(origin);
List<WebElement> oriui = ori.getOptions();
int size = oriui.size();
for (int i =0; i < size ; i++) {
String options = oriui.get(i).getText();
System.out.println(options);
}
Let's beautify your code first. https://codebeautify.org/javaviewer
WebElement origin = driver.findElement(By.xpath("//*[#id="ctl00_mainContent_ddl_originStation1 "]"));
Select ori = new Select(origin);
List oriui = ori.getOptions();
int size = oriui.size();
for (int i = 0; i < size; i++) {
String options = oriui.get(i).getText();
System.out.println(options);
First, to get the select element properly, pass the XPath as a String. Use the single quote or escape character as the element ID in the xpath also a nested String in this case.
Be like..
driver.findElement(By.xpath("//*[#id='ctl00_mainContent_ddl_originStation1']"));
Alternatively you can use By.id if you are calling it by ID only.
driver.findElement(By.id("ctl00_mainContent_ddl_originStation1"));
public void Test() throws Exception {
String URL = "https://rahulshettyacademy.com/dropdownsPractise/";
driver.get(URL);
WebElement origin = driver.findElement(By.id("ctl00_mainContent_ddl_originStation1"));
Select ori = new Select(origin);
List<WebElement> oriui = ori.getOptions();
for(WebElement ele : oriui) {
System.out.println(ele.getAttribute("text"));
}
}
OUTPUT:
Departure City
Adampur (AIP)
Ahmedabad (AMD)
Amritsar (ATQ)
......
Srinagar (SXR)
Vijayawada (VGA)
Vishakhapatnam (VTZ)
I have an ArrayList that has numbers in it in a form of Strings, that are taken from a WebElement List (Copied into it).
I have 2 of these and I would like to compare between them, But because they have some "," and "." in these numbers I have difficulty to do that.
I have tried to look into similar questions such as
How can I remove punctuation from input text in Java?
But have failed to implement it on my arrayList.
The lists in the code can be easily located as :
/ / ***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
and
***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
public static void WatchlistInstrumentsList(WebDriver driver, boolean finalstatus) throws InterruptedException
{
List<Integer> memoryOfSelectedi = new ArrayList<Integer>(); // Remembering the 'Clock = Green' instruments
int size = 2;
int forCounter1=0;
for (int i = 1; i < size ; i++) {
forCounter1=i;
// The selector of "Last" price = Streamer
listOfLastPrice1= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
// ***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
ArrayList<String> listCopyLastPrice1 = new ArrayList<String>();
for (WebElement element : listOfLastPrice1) {
listCopyLastPrice1.add(element.getText());
}
System.out.println("Number of Open stocks out of the list is: " +memoryOfSelectedi.size());
WatchlistCheckSocket(driver, listCopyLastPrice1, memoryOfSelectedi,listOfLastPrice1, forCounter1) ;
finalstatus = true;
}
public static void WatchlistCheckSocket(WebDriver driver,List listCopyLastPrice1,
List<Integer> memoryOfSelectedi, List<WebElement> listOfLastPrice1, int forCounter1) throws InterruptedException
{
// ******** CHANGE LATTER TO 180000 ******///
Thread.sleep(60000);
List<WebElement> listOfLastPrice2=null;
int size = 2;
int forCounter2;
for (int z = 0; z < size ; z++) {
listOfLastPrice2= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
size = listOfLastPrice2.size();
String NewPrice = listOfLastPrice2.get(z).getText();
System.out.println("Last Price is: " +listOfLastPrice2.get(z).getText());
}
// LIST #2 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS ///
// Put all Values of WebElement listOfLastPrice2 List, into a String array list //
ArrayList<String> listCopyLastPrice2 = new ArrayList<String>();
for (WebElement element : listOfLastPrice2) {
listCopyLastPrice2.add(element.getText());
}
// ****** COMPARE GREEN INSTRUMENTS, LIST1_Price VS LIST2_Price ****//
int sizeList=0;
while (sizeList<memoryOfSelectedi.size())
{
if (listCopyLastPrice1.get(memoryOfSelectedi.get(sizeList)) != listOfLastPrice2.get(memoryOfSelectedi.get(sizeList)).getText())
{
System.out.println("First price was: " +listCopyLastPrice1.get(memoryOfSelectedi.get(sizeList)));
System.out.println("Second price was: " +listCopyLastPrice2.get(memoryOfSelectedi.get(sizeList)));
}
sizeList++;
}}}
If I'll modify my list's syntax to that, would this help?
listCopyLastPrice2.add(element.getText().replaceAll("[^A-Za-z0-9]", ""));
I want to get text from all the check boxes given in a drop down box in order to compare those values with db. Please help me. I am able to count the size by options.size(), but unable to get the text/strings to compare with each string in db.
//Click on Select Box
Thread.sleep(500);
driver.findElement(By.xpath(".//*[#id='DivZone']/div/button")).click();
Thread.sleep(500);
List<WebElement> options =
driver.findElements(By.xpath("//input[contains(#name,
'multiselect_ddlZone')]"));
//List<WebElement> options = driver.findElements(By.cssSelector(".ui-
corner-all.ui-state-hover>span"));
List<String> all_elements_text=new ArrayList<>();
if(region!=null)
{
for(int i=1; i<options.size(); i++)
{
all_elements_text.add(options.get(i).getText());
System.out.println(options.get(i).getText());
boolean isThere = false;
for (int j = 0; j < region.size(); j++)
{
if
(options.get(i).getText().equalsIgnoreCase(region.get(j))) {
// Code to display warning
isThere = true;
}
}
if(isThere)
System.out.println(options.get(i).getText()+" is matched
with Database data");
else
System.out.println(options.get(i).getText()+" is not matched
with Database data");
}
}
If unfortunately getText() doesn't work, you should try using getAttribute("textContent") as below :-
System.out.println(options.get(i).getAttribute("textContent"));
Or try using getAttribute("innerHTML") as below :-
System.out.println(options.get(i).getAttribute("innerHTML"));
Right now, each "option" is an "input" WebElement, which will not have any text.
You may want to try searching for the list items, then pulling out the span content:
List<WebElement> options = driver.findElements(By.cssSelector("ul.ui-multiselect-checkboxes li label[for*='ddlZone'] span"));
Gave it a try on "www.tripadvisor.in", and able to make it (Used 'break' statement just to limit the loop in the example). Below is the code I tried on
public class SelectList {
WebDriver driver;
By currencyDrop = By.xpath(".//*[#id='CURRENCYPOP']/span");
By currency = By.xpath(".//*[#id='GLOBAL_CURRENCY_PICKER']/ul/li");
#Test
public void f() throws InterruptedException {
driver = new FirefoxDriver();
driver.get("https://www.tripadvisor.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(currencyDrop).click();
//Below is the list of options present in dropdown(per DB)
String[] expList = {"INR ₹ Indian Rupees",
"USD US$ U.S. Dollars",
"EUR € Euros"};
List <WebElement>countryList = driver.findElements(currency);
int i =0;
for(WebElement curr:countryList){
if (i>2){
break;
}
if (curr.getText().equals(expList[i])){
System.out.println("ActCurrency" + curr.getText());
System.out.println("ExpCurrency" + expList[i]);
i++;
}
}
}
}
Test case:
Check box needs to be checked and corresponding drop down value needs to be selected.
Issue:
Cannot click on the element as another element is overlapped on the required element. Error is
Element is not clickable at point (898.9500122070312, 16.5). Other
element would receive the click:
Command duration or timeout: 76 milliseconds
public class ProfileCreation {
public static WebDriver driver ;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
System.out.println("Profile Name ===>"+ timeStamp );
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://suite.simplify360.com");
driver.findElement(By.cssSelector(".form-login.first-input")).sendKeys("alexxm360#gmail.com");
driver.findElement(By.id("login_password")).sendKeys("Simplify360#");
driver.findElement(By.id("rp")).click();
driver.findElement(By.linkText("Listen")).click();
driver.findElement(By.xpath("//input[contains(#onclick,'createNewProfile();')]")).click();
driver.findElement(By.xpath("//input[#id='dashboardName']")).sendKeys(timeStamp);
System.out.println("Profile Name ===>"+ timeStamp );
WebElement slider = driver.findElement(By.xpath("//*[#id='slider-range-max']/a[2]"));
Actions move = new Actions(driver);
Action action = (Action) move.dragAndDropBy(slider, 30, 0).build();
action.perform();
WebElement permissionDropDown = driver.findElement(By.id("actionPerm"));
Select oselect = new Select(permissionDropDown);
List <WebElement> elementCount = oselect.getOptions();
// System.out.println("Count of Options"+elementCount.size());
int iSize = elementCount.size();
// For priting the values in permission
/*for(int i =0; i<iSize ; i++){
String sValue = elementCount.get(i).getText();
System.out.println("permissoin Values"+sValue);
}*/
oselect.selectByVisibleText("OPEN");
oselect.selectByVisibleText("WARN");
oselect.selectByVisibleText("BLOCK");
if (driver.findElements(By.cssSelector("a.cb-enable.selected")).size() > 0 ) {
driver.findElement(By.xpath("//span[contains(.,'Off')]")).click();
} else {
driver.findElement(By.xpath("//span[contains(.,'On')]")).click();
}
if(driver.findElements(By.id("reassignPeriodMins")).size() > 0){
WebElement caseAssociateMin = driver.findElement(By.id("reassignPeriodMins"));
Select timeSelect = new Select(caseAssociateMin);
WebElement firstSelectedOption = timeSelect.getFirstSelectedOption();
System.out.println("Default Selected Time"+firstSelectedOption.getText());
timeSelect.selectByVisibleText("45");
}
if(driver.findElements(By.id("replySetting")).size() > 0){
WebElement replySetting = driver.findElement(By.id("replySetting"));
Select replyType = new Select(replySetting);
WebElement firstSelectedOption = replyType.getFirstSelectedOption();
System.out.println("Default Selected Time"+firstSelectedOption.getText());
replyType.selectByVisibleText("REPLY");
replyType.selectByVisibleText("REPLYALL");
}
System.out.println( "checkboxes" + driver.findElements(By.className("shareCheck")).size());
int sizeOfUsers = driver.findElements(By.className("shareCheck")).size();
for (int i = 1; i <= sizeOfUsers; i++) {
boolean fname = driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[3]/input")).isEnabled();
if (fname == false){
String disblaedEmailID = driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[2]/div")).getText();
String loginEmailId = "nagarjun.reddy#in-rev.com";
if( disblaedEmailID == loginEmailId){
System.err.println("Check Box is disabled ====>"+disblaedEmailID);
}
System.err.println("i value==>"+ i);
i++;
System.err.println("selected email id will be =="+ driver.findElement(By.xpath(".//*[#id='basketusers']/tbody/tr["+i+"]/td[2]/div")).getText() );
//ISSUE IS HERE. CANNOT MOVE TO THE REQUIRED ELEMENT
jse.executeScript("arguments[0].scrollIntoView(true);",driver.findElement(By.xpath(".//*[#id='basketusers']/tbody/tr["+i+"]/td[2]/div")));
driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[3]/input")).click();
Select roleSelect = new Select(driver.findElement(By.xpath(".//*[#id='basketusers']/tbody/tr["+i+"]/td[4]/select")));
System.err.println("First selected role ====>"+ roleSelect.getFirstSelectedOption().getText());
roleSelect.selectByVisibleText("PROFILE AGENT");
System.err.println("Changed role ====>"+ roleSelect.getFirstSelectedOption().getText());
}
// System.err.println( driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[3]/input")));
}
// driver.findElement(By.xpath("//input[#value='Next']")).click();
}
}
Try adding a scroll up like this.
jse.executeScript("window.scrollBy(0,-250)", "");
This will just make the chekbox not to hid eunder navbar.
i tried locally and it worked.
In one of my application there is one table and 50 rows in it. now there is 50 different id for the all the table rows. my scenario is to fill the table row through the wen driver. so how can i perform this task ?
As far as I know we cant modify DOM via WebDriver, but you can do it using JavascriptExecutor
try this:
JavascriptExecutor js = (JavascriptExecutor) driver;
WebEelement tableCells = driver.findElements(By.cssSelector("table > tr > td"));
for (WebElement cell : tableCells) {
String randString = getRandomString(20);
js.executeScript("text('"+ randString +"')", cell);
}
private static String getRandomString(final int length) {
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}