Selenium java find multiple Displayed elements - java

I'm using Selenium with Java from the Mavenproject.
My code is working, I'm just wondering if it can be improved.
In the code below you can see I'm looking for a few elements and if they are displayed or not.
The issue is that I'm looking for tons of elements +- 50.
So I have about 50 of these lines. I'm struggling to find a more efficient way. Isn't a easier way of writing this down in 1 line searching for multiple elements and checking if all are displayed?
Like Find.... A,B,C,D,...,Y,Z .isDisplayed?
boolean function_detail_breadcrumb_1_displayed = driver.findElement(By.cssSelector("[data-core2='403']")).isDisplayed();
boolean function_detail_breadcrumb_2_displayed = driver.findElement(By.cssSelector("[data-core2='405']")).isDisplayed();
boolean function_detail_breadcrumb_3_displayed = driver.findElement(By.cssSelector("[data-core2='407']")).isDisplayed();
boolean function_detail_breadcrumb_4_displayed = driver.findElement(By.cssSelector("[data-core2='410']")).isDisplayed();
boolean function_detail_breadcrumb_5_displayed = driver.findElement(By.cssSelector("[data-core2='413']")).isDisplayed();

If you only want to check certain breadcrumbs:
String[] breadCrumbs = new String[]{"403", "405", "407", "410", "413"};
for (String breadCrumb : breadCrumbs) {
String selector = String.format("[data-core2='%s']", breadCrumb);
boolean breadCrumbDisplayed = driver.findElement(By.cssSelector(selector)).isDisplayed();
}

Note: I am assuming, you are checking whether all elements are displayed or not.
First, You find elements of the kinds:
List<WebElement> breadCrumbList = driver.findElements(By.cssSelector("Your selector"));
Then iterate through your breadcrumbs and check:
List<WebElement> breadCrumbList = driver.findElements(By.cssSelector("Your selector"));
boolean isAllDisplayed = true;
for(WebElement breadCrumb : breadCrumbList){
if(breadCrumb.isDisplayed() == false){
isAllDisplayed = false;
break;
}
}

Related

How to use navigate back in for each loop?

I want to click on an element inside a list and go to different page. In this page I m taking a string. Then I go back and do the same for others. But after one iteration my code can't find the second element and shuts down the browser. Am I using the navigator wrong?
Here is my code:
public MainPage ControlSorting() {
List <WebElement> listItems=driver.findElement(RESULTCONT).findElements(MEDIA);
String[] strImdb = new String[listItems.size()];
int l = 0;
for (WebElement ele1 : listItems) {
ele1.click();
WebElement element = getElementBy(ABOUTIMDB);
String a= element.getAttribute("ng-genre-action");
String[] parts = a.split(",");
strImdb[l]=parts[1];
l++;
driver.navigate().back();
}
return this;
}
After going back you have to re identify the object. Please add the following code inside for loop at the first line of your code.
listItems=driver.findElement(RESULTCONT).findElements(MEDIA);
This should work. Please try and let me know.

trim String and add to ArrayList

the variable TEST is equal to this
lazar108#hotmail.com_Hd_s lazar108#hotmail.com_Update_on the lazar108#hotmail.com_Ksks_ajsj
i want to pull each "product" out so i have an ArrayList equal to this
lazar108#hotmail.com_Hd_s
lazar108#hotmail.com_Update_on
lazar108#hotmail.com_Ksks_ajsj
Right now the only thing in my array list is lazar108#hotmail.com_Hd_s
How can i pull each "product" from the one variable (TEST) in a loop and add it to the ArrayList?
My code so far:
String TEST = result;
ArrayList<String> Products = new ArrayList<>();
boolean flag = true;
while(flag == true){
Products.add(TEST.substring(0, TEST.indexOf(' ')));
TEST = TEST.substring(TEST.indexOf(' ') + 1);
if(TEST.equals("")){
flag = false;
}else{
TEST = TEST.substring(1);
}
}
Your one step away from doing it. After the first iteration of your while loop, you do retrieve lazar108#hotmail.com_Hd_s, but after that the loop runs infinitely because the other parts of the string are not being accessed. The solution is to cut out the part you retrieved from the string each time you add it to Products. I should also note that this will only work if TEST ends with a space " ". Here is a way to approach this.
String TEST = result;
ArrayList<String> Products = new ArrayList<>();
boolean flag = true;
while(flag == true){
Products.add(TEST.substring(0,TEST.indexOf(' ')));
TEST = TEST.substring(TEST.indexOf(' '));//cutting the last email added from the string
if(TEST.equals(" ")){
flag = false;
}
else{
TEST = TEST.substring(1); //remove that space so that it doesn't get
//counted again in the next iteration
}
}
Seeing your input string doesn't simply have email separated by white space, I suggest you use Pattern and Matcher. First you need to define the email's pattern (you can google it), then use the example in this : http://www.tutorialspoint.com/java/java_regular_expressions.htm
An alternative one line solution using String.split() function:
List<String> products = Arrays.asList(TEST.split(" "));

java selenium webdriver Select from dropdown menu select by value ignore case sensitivity

I have a problem to select from dropdown menu by using SelectByValue ignoring case sensitivity.
For example:
Japan
Albania
As it is seen value is Japan. However, the value which I have can be "japan" or "Japan".
I can able to select by using. However, it takes considerable amount of time if the list is huge.
// get dropdown elements
Select dropdown = new Select(findElementHelper(by));
// get elements based on options from dropdown menu
List<WebElement> myElements = dropdown.getOptions(); //because of listing takes time
// test until value of element and given value is equal
String tempValue = value.trim();
for (WebElement option : myElements) {
if (tempValue.equalsIgnoreCase(option.getAttribute("value").trim())) {
// tryClick(option,value) did not work on ie
/*if (!tryClick(option,value)){
System.out.println(value + " is not selected");
return false;
} option.click(); //worked one
break;
}
}
I have tried Select class with proper input and it works much faster than my code. Is there any way to ignore case sensitivity in selectByValue.
Thanks for help
The Selenium implementation of selectByValue() searches for the given value using xpath instead of looping through all of the options. You should be able to change the xpath search to be change everything to lowercase instead. If you know there will only be one option with the given value then you can simplify this further by removing the List and for loop.
WebElement dropdownElement = findElementHelper(by);
String tempValue = value.trim().toLowerCase();
List<WebElement> matchingValues = dropdownElement.findElements(By.xpath(
".//option[lower-case(#value) = '" + tempValue + "']"));
for(WebElement matchingValue : matchingValues)
{
/* Do what you want with the options
if (!option.isSelected()) {
option.click();
} */
}
I don't work with Selenium in Java so I'm not able to test this but it should be pretty close. Let me know if this is faster.

How many times a text appears in webpage - Selenium Webdriver

Hi I would like to count how many times a text Ex: "VIM LIQUID MARATHI" appears on a page using selenium webdriver(java). Please help.
I have used the following to check if a text appears in the page using the following in the main class
assertEquals(true,isTextPresent("VIM LIQUID MARATHI"));
and a function to return a boolean
protected boolean isTextPresent(String text){
try{
boolean b = driver.getPageSource().contains(text);
System.out.println(b);
return b;
}
catch(Exception e){
return false;
}
}
... but do not know how to count the number of occurrences...
The problem with using getPageSource(), is there could be id's, classnames, or other parts of the code which match your String, but those don't actually appear on the page. I suggest just using getText() on the body element, which will only return the page's content, and not HTML. If I'm understanding your question correctly, I think that is more what you are looking for.
// get the text of the body element
WebElement body = driver.findElement(By.tagName("body"));
String bodyText = body.getText();
// count occurrences of the string
int count = 0;
// search for the String within the text
while (bodyText.contains("VIM LIQUID MARATHI")){
// when match is found, increment the count
count++;
// continue searching from where you left off
bodyText = bodyText.substring(bodyText.indexOf("VIM LIQUID MARATHI") + "VIM LIQUID MARATHI".length());
}
System.out.println(count);
The variable count contains the number of occurrences.
There are two different ways to do this:
int size = driver.findElements(By.xpath("//*[text()='text to match']")).size();
This will tell the driver to find all of the elements that have the text, and then output the size.
The second way is to search the HTML, like you said.
int size = driver.getPageSource().split("text to match").length-1;
This will get the page source, the split the string whenever it finds the match, then counts the number of splits it made.
You can try to execute javascript expression using webdriver:
((JavascriptExecutor)driver).executeScript("yourScript();");
If you are using jQuery on your page you can use jQuery's selectors:
((JavascriptExecutor)driver).executeScript("return jQuery([proper selector]).size()");
[proper selector] - this should be selector that will match text you are searching for.
Try
int size = driver.findElements(By.partialLinkText("VIM MARATHI")).size();

How can I determine if a HTML document is well formed or not in JAVA?

Heyy guys, I need to determine if a given HTML Document is well formed or not.
I just need a simple implementation using only Java core API classes i.e. no third party stuff like JTIDY or something. Thanks.
Actually, what is exactly needed is an algorithm that scans a list of TAGS. If it finds an open tag, and the next tag isn't its corresponding close tag, then it should be another open tag which in turn should have its close tag as the next tag, and if not it should be another open tag and then its corresponding close tag next, and the close tags of the previous open tags in reverse order coming next on the list. I've already written methods to convert a tag to a close tag. If the list conforms to this order then it returns true or else false.
Here is the skeleton code of what I've started working on already. Its not too neat, but it should give you guys a basic idea of what I'm trying to do.
public boolean validateHtml(){
ArrayList<String> tags = fetchTags();
//fetchTags returns this [<html>, <head>, <title>, </title>, </head>, <body>, <h1>, </h1>, </body>, </html>]
//I create another ArrayList to store tags that I haven't found its corresponding close tag yet
ArrayList<String> unclosedTags = new ArrayList<String>();
String temp;
for (int i = 0; i < tags.size(); i++) {
temp = tags.get(i);
if(!tags.get(i+1).equals(TagOperations.convertToCloseTag(tags.get(i)))){
unclosedTags.add(tags.get(i));
if(){
}
}else{
return true;//well formed html
}
}
return true;
}
Yeah string manipulation can seem like a pickle sometimes,
you need to do something like
First copy html into an array
bool tag = false;
string str = "";
List<string> htmlTags = new List();
for(int i = 0; i < array.length; i++)
{
//Check for the start of a tag
if(array[i] == '<')
{
tag == true;
}
//If the current char is part of a tag start copying
if(tag)
{
str += char;
}
//When a tag ends add the tag to your tag list
if(array[i] == '>')
{
htmlTags.Add(str);
str = "";
tag == false;
}
}
Something like this should get you started, you should end up with an array of tags, this is only pseudo code so it wont shouldn't compile
Don't think you can do this without undertaking a huge amount of work, would be much easier to use a third party package
Try validating against HTML4 or 4.1 or XHTML 1 DTD
"strict.dtd"
"loose.dtd"
"frameset.dtd"
Which might help !

Categories

Resources