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.
Related
Dynamically created text-box on add button click with same id and class-name not able to send text second/third text-box.
List<WebElement> clientidtxt = driver.findElements(By.xpath("//label[contains(.,'Client ID')]/following::input[#id='CId']"));
for (WebElement webElement1 : clientidtxt)
{
if(!clientidtxt.isEmpty())
{
clientId.sendKeys(Keys.ENTER);
clientId.sendKeys(uuid);
System.out.println(webElement1.getText());
}
}
I have already send text to first text-box but not able to send to the second or third ....
Your code is kinda confusing.
You are looping through a list of web elements but inside you check to see if the list is empty... it can't be if you are looping through the list so that part can be removed.
You are using a foreach but you aren't actually using webElement1 but instead are referencing clientId which isn't declared in the code you posted.
I've updated the code with a best guess. Try this and see if it's what you are looking for.
List<WebElement> clientidtxt = driver.findElements(By.xpath("//label[contains(.,'Client ID')]/following::input[#id='CId']"));
for (WebElement webElement1 : clientidtxt)
{
webElement1.sendKeys(Keys.ENTER); // What's this for? Can this be removed?
webElement1.sendKeys(uuid);
System.out.println(webElement1.getText()); // if webElement1 is an INPUT, this needs to be webElement1.getAttribute("value") to return what the INPUT contains
}
I'm trying to click on all the search results with a loop and get the title strings from each of the results. So it would click on a result try to extract the string.
String title = null;
List <WebElement> links = driver.findElements(By.className("thumbnail"));
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
for(int i=0; i<1; i++){
links = driver.findElements(By.className("thumbnail")); // this step is must, because whenever you go to other page all store WebElements in a list will wash out
links.get(i).click();
//it opens the search result in a new tab and gains focus on that tab
WebDriverWait wait = new WebDriverWait(driver, 10);
By addItem = By.xpath("//*[#id=\"HEADING\"]");
// get the "Add Item" element
WebElement element1 = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));
wait.until(ExpectedConditions.stalenessOf(element1));
if(!driver.findElements(By.xpath("//*[#id=\"HEADING\"]")).isEmpty()) {
title = driver.findElement(By.xpath("//*[#id=\"HEADING\"]")).getText();
}
else {
System.out.println("Title is missing");
}
System.out.println(title);
driver.switchTo().window(tabs.get(0)); //Switching to first tab
}
The code is extracting the title on the first page rather than the page it clicked on. I'm also trying to extract other strings such as address, email, etc but i'm just testing this out. How do I fix this? Any help would be appreciated, thank you!
There were a few things that I changed.
I moved all your locators (and some other declarations) to the top and outside of the loop so they aren't redeclared inside the loop and so that they can be referenced by the .findElement() calls.
Since you are only using the current window handle, changed the variable type to String and just got the current window handle (instead of the collection of handles) so that you can switch back to the main tab at the end of the loop.
Moved the staleness check right after the click since that's where you need it and changed it to wait for the thumbnail that was just clicked.
Changed the XPath locator to use ID since that's all you were referencing. It's faster, shorter, and easier to read.
The second wait now waits for the collection of elements and then uses that collection to test for empty and get the text of the first in the collection.
By addItemLocator = By.id("HEADING");
By thumbnailsLocator = By.className("thumbnail");
List<WebElement> links = driver.findElements(thumbnailsLocator);
String originalTab = driver.getWindowHandle();
Set<String> tabs = driver.getWindowHandles();
WebDriverWait wait = new WebDriverWait(driver, 10);
for(int i = 0; i < links.size(); i++)
{
links = driver.findElements(thumbnailsLocator); // this step is must, because whenever you go to other page all store WebElements in a list will wash out
links.get(i).click();
// it opens the search result in a new tab and gains focus on that tab
// switch to the new window
for(String handle : driver.getWindowHandles()){
if (!handle.equals(originalTab))
{
driver.switchTo().window(handle);
break;
}
}
// get the "Add Item" element
List<WebElement> addItems = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(addItemLocator));
if(!addItems.isEmpty())
{
System.out.println(addItems.get(0).getText());
}
else
{
System.out.println("Title is missing");
}
driver.close(); // close current tab
driver.switchTo().window(originalTab); // switch to original tab
}
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;
}
}
I am facing problem while checking the clickable web element.
So i have to check the alphabetic series and some of the alphabet are clickable and some are not clickable.
i used for loop for it starting with xpath of alphabet 'A'
and going in loop till alphabet 'Z'.
but as soon as xpath of alphabet A is click & pass it goes to alphabet 'B'
which is not clickable and due to this whole script is getting fail.
here is the code
for(int j=3; j<=26;j++) {
String T1 =".//*[#id='twctvEl']/div/div/div[1]/ul/li[";
String T2 = "]/a";
String T12 = T1+j+T2;
chrome.findElement(By.xpath(T12)).click();
String alpha =chrome.findElement(By.xpath(T12)).getText();
System.out.println("checking the alphabet"+alpha);
}
Please advice here
NOTE: In the series of alpha bet from A-Z only B,Q,S,X,Y,Z are not clickable rest all are clickable.
You can add waits before element to become clickable:
for(int j=3; j<=26;j++)
{
String T1 =".//*[#id='twctvEl']/div/div/div[1]/ul/li[";
String T2 = "]/a";
String T12 = T1+j+T2;
WebElement el = chrome.findElement(By.xpath(T12));
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement el= wait.until(ExpectedConditions.elementToBeClickable(element));
el.click();
String alpha =el.getText();
System.out.println("checking the alphabet"+alpha);
}
You can check if the element is visible and enabled before clicking on it
WebElement letter = chrome.findElement(By.xpath(T12));
if (letter.isDisplayed() && letter.isEnabled()) {
letter.click();
}
Well, it seems that when you click the element "A", it take you to another page or context and for this reason, during next iteration chrome driver is not able to find your Element "B" using xPath.
I have managed to successfully grab the href links using JSoup. I have also managed to grab the relative value and absolute value of a href for a single link. As shown below:
//works perfectly, website: bbc.co.uk
Document document = Jsoup.connect(url).get();
Element link = document.select("a").last();
String relHref = testlink.attr("href");
String absHref = testlink.attr("abs:href");
System.out.println(relHref);
System.out.println(absHref);
//output:
relHref: /help/web/links/
absHref: http://www.bbc.co.uk/help/web/links/
I can even use Element link = document.select("a").first(); and this also works. However, when I try and add this in a loop to iterate through all of the grabbed links and print out each link, it doesn't give me the expected results. Here is my code:
//not working
Elements links = document.select("a");
for(int i=0; i<links.size(); i++){
String relHref = links.attr("href");
String absHref = links.attr("abs:href");
System.out.println(relHref);
System.out.println(absHref);
}
//output
http://m.bbc.co.uk
http://m.bbc.co.uk
http://m.bbc.co.uk
....
I know the links array of type Elements has the correct data, and if I try and print the elements in the links array it displays all of the href tags i.e.
for (Element link : links) {
System.out.println(link);
}
//output 116 links:
mobile site
<img src="http://static.bbci.co.uk/frameworks/barlesque/2.72.5/orb/4/img/bbc-blocks-dark.png" width="84" height="24" alt="BBC">
Skip to content
<a id="orb-accessibility-help" href="/accessibility/">Accessibility Help</a>
....
But how do I get the relHref and absHref for an array to work? Instead my code just prints out the first link over and over again. I've been going at this for hours, so I'm probably making a silly mistake somewhere but help is appreciated!
Thanks.
On this line:
String relHref = links.attr("href");
...how is it supposed to know you're talking about the ith link? (It doesn't: Elements#attr always returns the value for the first entry in the Elements collection.)
You want
String relHref = links.get(i).attr("href");
...which gets the specific link you're interested in via Elements#get, then uses Node#attr on it.
That said, though, I would just use the enhanced for loop:
for (Element link : document.select("a")) {
String relHref = link.attr("href");
String absHref = link.attr("abs:href");
System.out.println(relHref);
System.out.println(absHref);
}
...unless you need i for something.
You need to use the Elements method, get(int index) inside of your for loop to get each Element held by your Elements.
e.g.,
Elements links = document.select("a");
for(int i=0; i < links.size(); i++) {
Element ele = links.get(i);
/// use ele here to extract info from each Element
}