How to differentiate between image link and href link in selenium webdriver? - java

I am trying to get the name of the links of wikipedia home page in selenium webdriver . In the home page there is a table at the bottom which contains the link of wikipedia sister projects like Media-wiki, meta wiki etc . But after running the code I am getting 24 links. But in the webpage there are only 12 links. My suspicion is it is taking the links of images also.
package tcsWebmail;
import java.io.File;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WikiPediaLinks {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/Main_Page");
System.out.println(driver.getTitle());
WebElement Block=driver.findElement(By.xpath("//*[#id='mp-sister']/table//a[not(img)]"));
List<WebElement> Links= Block.findElements((By.tagName("a")));
System.out.println("Printing the no of items in block");
int i=0;
for ( i=0;i<Links.size();i++){
System.out.println(Links.get(i).getText());
}
System.out.println("The no of items are"+Links.size());
driver.quit();
}
}

Your XPath includes images as you suspect. In order to get a that don't contain a descendant img, you can to use XPath below:
//*[#id='mp-sister']/table//a[not(img)]
or
//*[#id='mp-sister']/table//a[not(descendant::*[local-name() = 'img'])]
See code below:
List<WebElement> Links= driver.findElements(By.xpath("//*[#id='mp-sister']/table//a[not(img)]"));

In for loop put another condition to check to validate imgage (img) or link (href)
List<WebElement> Links= Block.findElements((By.tagName("a")));
System.out.println("Printing the no of items in block");
for ( int i=0;i<Links.size();i++)
{
if(Links.get(i).getAttribute("href").contains("http://")
{System.out.println(Links.get(i).getText());
}
driver.quit();
}
}

Related

How to find the auto suggestion on google search with Xpath

With Selenium webdriver, I am trying search 'Selenium' in google search box, which provides auto suggestions of several texts. Then I am trying to click one particular text from auto suggestions list. It seems though, my Xpath is not working.
Below is the code I wrote:
package com.initial.selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GoogleSearch {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Shahid\\eclipse-
workspace\\InitialSeleniumProject\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.xpath("//*[#name='q']")).sendKeys("selenium");
List < WebElement >
mylist=driver.findElements(By.xpath("//ul[#role='listbox']//li/descendant::div[#class='sbl1']/span"));
System.out.println(mylist.size());
for (int i = 0; i < mylist.size(); i++) {
System.out.println(mylist.get(i).getText());
if (mylist.get(i).getText().contains("Selenium Benefits")) {
mylist.get(i).click();
break;
}
}
}
Try this:
List<WebElement> options = new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("//ul[#role='listbox']//li/descendant::span"), 0));
System.out.println("no. of suggestions:"+options.size());
for(int i=0;i<options.size();i++) {
System.out.println(options.get(i).getText());
}
In this case, the error you're getting (a null result) is because the ul element you're targeting doesn't contain any elements.
So, in this case, you're going to change your target. Instead of doing:
ul[#role='listbox']
Do
li[#role='presentation']
And that will result in
//li[#role='presentation']/descendant::div[#class='sbl1']/span
Which returns the span you're trying to get.

Firepath shows matching nodes but does not print

I am trying to capture the prices in a list and print them. However the execution stops in the search result page and does not print the prices. I think it is because of the level of Xpath (probably I am not selecting from the upper levels?). I am confused because the Xpath I have created, when I use that in the Firepath it selects 39 matching nodes.
Thanks in advance for your time and advice.
Code:
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Flight {
public static WebDriver driver;
//This following section is for browser and getting the url
public static WebDriver browser(){
driver= new FirefoxDriver();
driver.get("https://www.orbitz.com/Flights");
return driver;
}
//this following section is getting the properties of the page
public static void getPageProperties(String ff,String ft, String fd, String rd){
WebElement flyFrom= driver.findElement(By.id("flight-origin"));
WebElement flyTo= driver.findElement(By.id("flight-destination"));
WebElement flyDate= driver.findElement(By.id("flight-departing"));
WebElement returnDate= driver.findElement(By.id("flight-returning"));
WebElement flight_search_btn= driver.findElement(By.id("search-button"));
flyFrom.sendKeys(ff);
flyTo.sendKeys(ft);
flyDate.sendKeys(fd);
returnDate.sendKeys(rd);
flight_search_btn.click();
}
// this following section will have the arguments that we will provide for flight search
public static void testFligthSearch(){
Flight f= new Flight();
f.browser();
f.getPageProperties("MSP", "SEA", "05/01/2017", "05/05/2017");
List<WebElement> pricelist= driver.findElements(By.xpath("//span[contains(#class,'dollars')]"));
for(WebElement e: pricelist){
System.out.println("The prices are: " + e.getText());
}
}
public static void main (String [] args){
Flight f= new Flight();
f.testFligthSearch();
}
}
Problem: No price is printed.
You are facing this problem because all the results have not been loaded yet so you have to wait until all search results are loaded, so you need to wait until the search results progress bar has reached 100% as following :
WebElement progressBar = driver.findElement(By.cssSelector("#acol-interstitial > div > div"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.attributeContains(progressBar, "style", "width: 100%;"));
List<WebElement> pricelist= driver.findElements(By.cssSelector("ul#flightModuleList div.offer-price.urgent > span.visuallyhidden"));
for(WebElement e: pricelist){
System.out.println("The prices are: " + e.getText());
}

counting radio buttons not working with multiple tag names

File file = new File("D:\Selenium 2.48\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver=new InternetExplorerDriver();
driver.get("http://www.yatra.com/");
driver.manage().window().maximize();
List<WebElement> radio = driver.findElements(By.tagName("a"));
System.out.println(radio.size());
here is the new code, and i am able to lacate xpath now .thanks for it.But issue is with a white page which comes and result is zero .The original page takes some time.
please find the link
i wanted to count the number of radio buttons.
but i was not able to . I tried finding it by tag name and the result is zero.
The HTML is bit complicated to my understanding as in radio buttons , there is no input .hence i cannot find by input[#type=] etc
Please help me in this regard .
You should locate the right indicator for these ratios
Recommend you to use this xpath
//a[#data-flighttrip]
Here's my script
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class TestSelenium {
static WebDriver driver;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "res/chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
driver = new ChromeDriver(capabilities);
driver.get("http://www.yatra.com/");
List<WebElement> radio = driver.findElements(By.xpath("//a[#data-flighttrip]"));
System.out.println(radio.size());
driver.quit();
}
}
Here's console output
Starting ChromeDriver (v2.9.248315) on port 14427
3
Tried with IEDriver
import java.io.File;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class TestSelenium {
static WebDriver driver;
public static void main(String[] args) throws Exception {
File file = new File("D:\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver driver=new InternetExplorerDriver(cap);
driver.get("http://www.yatra.com/");
driver.manage().window().maximize();
List<WebElement> radio = driver.findElements(By.xpath("//a[#data-flighttrip]"));
System.out.println(radio.size());
driver.quit();
}
}
Result
Started InternetExplorerDriver server (64-bit)
2.52.0.0
Listening on port 6267
Only local connections are allowed
3
I think you need to wait for things to settle down and the page to load via WebDriverWait:
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.trip-type")));
Here, we are waiting for the trip type container to become visible, which, I assume, is a good indication that at least the relevant part of the page is loaded.
Then, you can count the links:
List<WebElement> radio = driver.findElements(By.tagName("a"));
System.out.println(radio.size());
Note that the radiobuttons are not actually HTML radio input elements in your case - these are just links with preceding "radiobutton"-like icons:
<a class="type-active" href="javascript:void(0);" data-flighttrip="O">
<i class="sprite-booking-engine ico-be-radio"> </i>
One Way
</a>
So, if you want to count these types of links anywhere on the page, you may check for the presence of the i child element with a ico-be-radio class with the following XPath expression:
List<WebElement> radio = driver.findElements(By.xpath("//a[contains(i/#class, 'ico-be-radio')]"));
System.out.println(radio.size());
But, if you want to just check how many "trip type" links are there, just get all of the a elements inside the "trip type" container:
WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement tripType = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.trip-type")));
List<WebElement> radio = tripType.findElements(By.tagName("a"));
System.out.println(radio.size());

How to count number of images available on a web page using selenium webdriver?

How to count number of images available on a web page using selenium webdriver? The web page contains a lots of image some are visible and some are hidden (display:none). I only wants to count images which are visible(not hidden).
I tried this but it doesn't work for only visible images.
#Test
public void imagetest()
{
driver.get("http://uat.tfc.tv/");
List<WebElement> listwebelement = driver.findElements(By.className("img-responsive"));
int i=0;
for (WebElement Element : listwebelement) {
i = i+1;
System.out.println(Element.getTagName());
System.out.println(Element.getText());
String link = Element.getAttribute("alt");
System.out.println(link);
}
System.out.println("total objects founds " + i);
}
Here you wanted to find out the no. of images in a page, so better check with tag name like below:
driver.findElements(By.tagName("img")
Here is the complete code for your reference
#Test
public void findNoOfDisplayeImages() throws InterruptedException
{
WebDriver driver=new FirefoxDriver();
Integer counter=0;
driver.get("http://uat.tfc.tv/");
Thread.sleep(20000);
List<WebElement> listImages=driver.findElements(By.tagName("img"));
System.out.println("No. of Images: "+listImages.size());
for(WebElement image:listImages)
{
if(image.isDisplayed())
{
counter++;
System.out.println(image.getAttribute("alt"));
}
}
System.out.println("No. of total displable images: "+counter);
driver.close();
}
You need to apply isDisplayed() check on each image element in the loop:
for (WebElement Element : listwebelement) {
if (!Element.isDisplayed()) {
continue;
}
...
}
package p1;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CountImages {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","/home/mcastudent/Downloads/software/geckodriver" );
WebDriver driver=new FirefoxDriver();
driver.get("https://opensource-demo.orangehrmlive.com/index.php/dashboard");
List<WebElement> listImages=driver.findElements(By.tagName("img"));
System.out.println("No. of Images: "+listImages.size());
}
}

How to select a field from html table using Selenium web driver in java

In my web page i have a html table and it contains multiple radio button. I want to select one radio button. So far i am able to find the values from the table but not able to select. This is my code: I am getting error on syntax aname.click();
Error is "The method click() is undefined for the type String"
import java.io.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SendTxn1 {
static WebDriver d1=null;
public static void main(String[] args) throws IOException, InterruptedException
{
File file1=new File("C:\\Selenium\\IEDriverServer_Win32_2.35.3\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver",file1.getAbsolutePath());
d1= new InternetExplorerDriver();
d1.get("http://10.00.00.107/");
WebElement table_element = d1.findElement(By.id("tblSendMoneyPayoutAgents"));
List<WebElement> tbl_rows=table_element.findElements(By.xpath("id('tblSendMoneyPayoutAgents')/tbody/tr"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tbl_rows.size());
int row_num,col_num;
row_num=1;
col_num=1;
String aname;
for(WebElement trElement : tbl_rows)
{
List<WebElement> tbl_col=trElement.findElements(By.xpath("td"));
for(WebElement tdElement : tbl_col)
{
aname = tdElement.getText();
if(aname.equals("VNM - VN Shop Herat"))
aname.click()l
break;
System.out.println(aname);
col_num++;
}
row_num++;
}
}
}
I think you need to use executeScript to select your radio button. This method executes a javascript string. Think of it as doing eval, but from Selenium. Depending on what version of Selenium you are using, you can cast your webdriver to a JavascriptExecutor, and then call executeScript, e.g.
((JavascriptExecutor) d1).executeScript("alert('replace the alert with the code to select your radio button');");
EDIT
If you don't want to use executeScript, you need to get the WebElement that corresponds to your radio button and then call its click method. In your case, you are trying to call click on the string returned by getText, hence your error :). So you are missing one more step that selects the radio buttons from your table cell.
Something along the lines of (the xpath query might be wrong)
List<WebElement> radio_buttons = tdElement.findElements(By.xpath('input[type=radio]'));
EDIT 2
To spell out the answer for you in copy-paste-able form, replace
aname = tdElement.getText();
if(aname.equals("VNM - VN Shop Herat"))
aname.click();
with
if(tdElement.getText().equals("VNM - VN Shop Herat")) {
List<WebElement> radio_buttons = tdElement.findElements(By.xpath('input[type=radio]'));
for(WebElement radio : radio_buttons) {
//now check which radio you want to click
}
}

Categories

Resources