Open every link in loop (Selenium) - java

I just cracked my head trying to find how make it work. I am trying to force Selenium open link by link, but it opens on first link again and again, console output shows that loop is working correctly. Tried to use while loop but it doesn`t work too. I am trying to open link after link and change number of the li element to open further link.
for (int footer_links = 1; footer_links < 6; footer_links++) {
WebElement self_service_bi = driver.findElement(By.xpath("//div/div/ul/li['$footer_links']/a"));
self_service_bi.click();
File srcFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File targetFile1 = new File("D:\\DataPineScreenshots\\" + driver.getTitle() + ".png");
FileUtils.copyFile(srcFile1, targetFile1);
driver.navigate().back();
System.out.print(footer_links + "\n");
}

fix your syntax
By.xpath("//div/div/ul/li['$footer_links']/a")
by
By.xpath("//div/div/ul/li[" + footer_links + "]/a")

driver.findElement will always return the first element of the type. Use driver.findElements function to get list of all matching the given xpath. But dont do that in loop cause everytime it will open the same link.
Try out like:
List<String> lstUrls = new ArrayList<String>();
List<WebElement> lstEle = driver.findElements(By.xpath("//div/div/ul/li['$footer_links']/a"));
for (WebElement element : lstEle)
lstUrls.add(element.getAttribute("href"));
for (String string : lstUrls) {
driver.get(string)
File srcFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File targetFile1 = new File("D:\\DataPineScreenshots\\" + driver.getTitle() + ".png");
FileUtils.copyFile(srcFile1, targetFile1);
driver.navigate().back();
System.out.print(footer_links + "\n");
}

Related

How to solve "org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"" selenium error

I'm going to get the default selected value of the below dropdown
I wrote below code to do it.
Select selectyear = new Select(driver.findElement(By.id("year")));
WebElement year = selectyear.getFirstSelectedOption();
String selectedoption = year.getText();
But this throws the following error
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"
How can I fix this? same code is working perfectly for dropdowns that don't have "value" attribute.
The only explanation is there is another element with id year, the input tag.
Put this code before Select selectyear = new Select(driver.findElement(By.id("year")));:
List<WebElement> elements = driver.findElements(By.id("year"));
for (WebElement element: elements) {
System.out.println("Tag: " + element.getTagName());
System.out.println("Text: " + element.getText());
System.out.println("Location: " + element.getLocation());
}
Solution is relative xpath for the select: select[#id='year']

How to filter WebImages by a specific attribute?

I'm trying to write an Program that will automatically make a google-pictures-search and download the first image of the given String.
I'm doing it all with selenium webdriver for Google, but I can change it tho. I tried to filter the results, but the only thinks that appears different to me is the "data-atf"-attribute. I want to download the first, so it should be on zero, but how Can I search after that? Besides the other attributes always change because of the different String that is given.
String = "German Shepherd"
ChromeDriver driver = new ChromeDriver();
driver.get("https:/google.com/search?q=" + String +
"&source=lnms&tbm=isch&sa=X&ved=0ahUKEw
iXlMO0nq_jAhUEzaQKHVVXC50Q_AUIEygE&biw
=834&bih=770");
//and then I've got something like this
//wont work because cssSelector is always different
WebElement img = driver.findElement(By.cssSelector("#selector"));
BufferedImage buffer = ImageIO.read(new URL(img.getAttribute("src")));
ImageIO.write(buffer, "png", new File("image.png"));
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.close();
}
Credits for the second part to: Save/copy to clipboard image from page by chrome console
I need help most importantly to filter the result and after that helping to download would be highly appreciated.
If you want to filter the images to the only those which have data-atf attribute the easiest is doing it via XPath selector
//img[#data-atf]
alternatively, if you want only children of "Search Results":
//h2[text()='Search Results']/parent::*/descendant::img[#data-atf]
Of course you can also filter images in Java code using Stream.filter() function
List<WebElement> allImages = driver.findElements(By.tagName("img"));
System.out.println("All images #: " + allImages.size());
List<WebElement> imagesWithDataAtf = allImages
.stream()
.filter(image -> image.getAttribute("data-atf") != null)
.collect(Collectors.toList());
System.out.println("Images with data-atf attribute #: " + imagesWithDataAtf.size());

How to switch tab using for loop in Selenium Webdriver

I struggle with the problem of not being able to switch between tabs using the loop in Selenium WebDriver. I can do this at once, but I need to use the code repeatedly, in a loop.
Here comes the error:
"Exception in thread" main "org.openqa.selenium.NoSuchWindowException: Unable to locate window"
My code can find all the elements, open a link in a new tab, close it. However, it can not perform this operation again with the next element.
Here is my code( I'm using Firefox):
List<WebElement> allElements = driver.findElements(By.className("_4zhc5"));
int s = allElements.size();
System.out.println("total users to check: " + allElements.size());
for (int i = 0; i < s; i++) {
allElements = driver.findElements(By.className("_4zhc5"));
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
allElements.get(i).sendKeys(selectLinkOpeninNewTab);
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
Thread.sleep(3000);
}
driver.close();
Thread.sleep(2000);
}
I also created a prototype page using jsfiddle. The error appears on the second attempt to execute the code. Just the script does not click on another element called "lovely"
You need to switch back to the original window where the links are.
Click on one if the links
Switch to that tab
Close tab
Switch back to default window where you are getting the links
Easiest way is to store the "original" window and switch back to that one all the time.
winHandleBefore = driver.getWindowHandle();
when closing the tab
driver.close();
driver.switchTo().window(winHandleBefore)
/*the second "for loop" will not help you so u should use another logic with another condition it will switch using while loop and hasNext method
try it: */
List allElements = driver.findElements(By.className("_4zhc5"));
int s = allElements.size();
System.out.println("total users to check: " + allElements.size());
for (int i = 0; i < s; i++) {
allElements = driver.findElements(By.className("_4zhc5"));
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
allElements.get(i).sendKeys(selectLinkOpeninNewTab);
Set<String>windowat=driver.getWindowHandles();
Iterator<String>itro=windowat.iterator();
while(itro.hasNext()) {
String currntpage=itro.next();
driver.switchTo().window(currntpage);
String thetitle=driver.getTitle();
System.out.println(thetitle); }

Java Selenium WebDriver unable to place first item into basket

Following is short program & in the following web site:
https://uk.webuy.com/search/index.php?stext=*&section=&catid=956
I am trying to click the first three product's "I want to buy this item" button &
view them in the VIEW BASKET at the right side of the page.
For some reason, I am able to see the second and third product only. For some reason, the first product never makes it to the basket, & it does not produce an error.
Only when I change the following line:
allButtons.get(0).click();
to:
allButtons.get(0).click();
allButtons.get(0).click();
allButtons.get(0).click();
I will see one occurrence of the first product in the basket.
What am I doing wrong? Is there something missing that is causing this problem?
Using Java 1.8
Selenium WebDrive Version #2.48
Mac OS Version #10.11.13
Thank you
public class ZWeBuy {
static WebDriver driver;
#Test
public void testProductPurchaseProcess() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://uk.webuy.com/search/index.php?stext=*&section=&catid=956");
closePopupIfPresent();
//xpath for all product names in this page
List<WebElement> allNames = driver.findElements(By.xpath("//div[#class='searchRecord']/div[2]/h1/a"));
List<WebElement> allButtons = driver.findElements(By.xpath("//div[#class='action']/div/a[2]/div/span"));
System.out.println("Total names = "+ allNames.size());
System.out.println("Total buttons = "+ allButtons.size());
System.out.println("I= " + 0 + " PRDCT: --- " +allNames.get(0).getText());
allButtons.get(0).click();
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("html/body/div[5]/div[1]/div[3]/div[5]/div[1]/div[1]/div[3]/div/a[2]/div/span")));
System.out.println("I= " + 1 + " PRDCT: --- " +allNames.get(1).getText());
allButtons.get(1).click();
System.out.println("I= " + 2 + " PRDCT: --- " +allNames.get(2).getText());
allButtons.get(2).click();
}
public static void closePopupIfPresent(){
Set<String> winIds = driver.getWindowHandles();
System.out.println("Total windows -> "+ winIds.size());
if(winIds.size() == 2){
Iterator<String> iter = winIds.iterator();
String mainWinID = iter.next();
String popupWinID = iter.next();
driver.switchTo().window(popupWinID);
driver.close();
driver.switchTo().window(mainWinID);
}
}
}
Your code isn't functional. Popup closing logic doesn't work, its actually not a separate window, its a dialog box within the same window. You should also consider simplifying your selectors. Alright enough said, here is working and tested code.
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://uk.webuy.com/search/index.php?stext=*&section=&catid=956");
WebElement element;
try {
element = driver.findElement(By.cssSelector(".deliver-component-wrapper>a>div"));
System.out.println("Closing pop up");
element.click();
} catch (NoSuchElementException e) {
System.out.println("Alright, no such dialog box, move on");
}
List<WebElement> buyButtons = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(
"span.listBuyButton_mx")));
Assert.assertTrue("Less than three buttons found", buyButtons.size() >= 3);
for (int i = 0; i < 3; i++) {
WebElement buyButton = buyButtons.get(i);
wait.until(ExpectedConditions.elementToBeClickable(buyButton)).click();
System.out.println("Clicked Buy Button " + (i + 1));
}
WebElement basketCount = wait
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#buyBasketRow>td.basketTableCell")));
System.out.println(basketCount.getText());
driver.quit();
It prints
Closing pop up
Clicked Buy Button 1
Clicked Buy Button 2
Clicked Buy Button 3
3 item/s
Your browser could not render that first button. you may put wait.until() method before each click event.
try this
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[5]/div[1]/div[3]/div[5]/div[1]/div[1]/div[3]/div/a[1]/div/span")));
allButtons.get(0).click();

how to use List<WebElement> webdriver

I am creating an automatic test for some webs and I'm using WebDriver, TestNG and code that is written in Java. On the page is shown register of categories, in parentheses is number of auctions and i need to get this number as variable.
I use this code
By bycss =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse = driver.findElement(bycss );
String text_vse1_1 = number1_1_vse.getText();
but I get only first number and i need to get all. Someone advised me that I should use List. But when i use it, i get only
[[[[[[[FirefoxDriver: firefox on WINDOWS (7e6e0d0f-5cbb-4e48-992f-26d743a321a5)] -> css selector: .list.list-categories>li:first-child]] -> xpath: ..]] -> xpath: .//*], [[[[[[FirefoxDriver: firefox on WINDOWS (7e6e0d0f-5cbb-4e48-992f-.....
code:
By bycss2 =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse2 = driver.findElement(bycss2 );
WebElement parent1 = number1_1_vse2.findElement(By.xpath(".."));
List<WebElement> childs1 = parent1.findElements(By.xpath(".//*"));
System.out.println(childs1);
link to the website
screenshot -> image with the number
can anyone advise me please?
Try the following code:
//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
System.out.println(e.getText());
}
It will returns with the whole content of the <li> tags, like:
<a class="extra">Vše</a> (950)</li>
But you can easily get the number now from it, for example by using split() and/or substring().
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemědělské objekty (5)
Number==>5
Name + Number===>Komerční objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
System.out.println("Size of List: "+myElements.size());
for(WebElement e : myElements)
{
System.out.print("Text within the Anchor tab"+e.getText()+"\t");
System.out.println("Anchor: "+e.getAttribute("href"));
}
//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.

Categories