import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Demo27 {
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("file:///C:/Users/Administrator/Desktop/listDropdown.html");
WebElement listElement=driver.findElement(By.id("countrySelect"));
Select select=new Select(listElement);
List<WebElement> elements=select.getOptions();
int count=elements.size();
HashSet<String> set=new HashSet<String>();
for(int i=0;i<count;i++)
{
WebElement singleElement=elements.get(i);
String text=singleElement.getText();
if(!set.add(text))
{
System.out.println(text+"is duplicated");
}
}
driver.close();
}
}
You can write a logic this way. I have created an ArrayList to capture the duplicate values. I will have it for reference if the incoming text is found in the duplicate list. If it is not present, then i will print it. Otherwise, i will just ignore. This way you can suppress the second duplicate text to be printed
boolean isSet = false;
List<String> duplicates = new ArrayList<String>();
if((isSet = set.add(text))){
//this will get printed for only unique values added
System.out.println(text+"is unique");
}
else{
if(!duplicates.contains(text)){
duplicates.add(text);
System.out.println(text+"is first duplicate");
}
}
Related
Hey all I have a question.
My assignment is that my program takes a command-line argument and then prints out the data.
I managed to navigate to the desired page and also print out the data I need but I did it with .sendKeys("name i need here"). Is it possible that at the start there would be like a question "what name do you want to type in" and you would then type the name in the command-line and everything else would play out the same?
Here's my code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By.ByXPath;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.List;
public class Scraper {
public static void main( String[] args ) throws IOException
{
System.setProperty("webdriver.chrome.driver", "D:/Chrome/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.basketball-reference.com/");
driver.findElement(By.xpath("//*[#id='header']/div[3]/form/div/div/input[2]")).sendKeys("Luka Dončić");
driver.findElement(ByXPath.xpath("//*[#id='qc-cmp2-ui']/div[2]/div/button[3]")).click();
driver.findElement(ByXPath.xpath("//*[#id='header']/div[3]/form/input[1]")).click();
driver.findElement(ByXPath.xpath("//*[#id='players']/div[1]/div[1]/strong/a")).click();
WebElement element = driver.findElement(By.id("div_per_game"));
List<WebElement> trojke = element.findElements(By.cssSelector("td[data-stat='fg3a_per_g']"));
List<WebElement> sezona = element.findElements(By.xpath("//*[#id='per_game']/tbody/tr/th/a"));
for (WebElement s: sezona)
{
System.out.println(s.getText());
}
for (WebElement t : trojke)
{
System.out.println(t.getText());
}
}
}
So instead of sendKeys("Luka Dončić") that automatically puts the name in the search box of a page I want to write the name myself in command line and when I press enter or something the rest would execute the same. Is it possible?
Here's the page I want to send the name to in the search box: https://www.basketball-reference.com/
Oh yes and I'm using Java with Selenium and Maven.
Before sending the text to the web element you can read the user input from console
import java.util.Scanner;
Scanner my_scan = new Scanner(System.in);
String my_text = my_scan.nextLine();
so now you can send the my_text
driver.findElement(By.xpath("//*[#id='header']/div[3]/form/div/div/input[2]")).sendKeys(my_text);
the entire code will look like this:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By.ByXPath;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
public class Scraper {
public static void main( String[] args ) throws IOException
{
System.setProperty("webdriver.chrome.driver", "D:/Chrome/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.basketball-reference.com/");
Scanner my_scan = new Scanner(System.in);
String my_text = my_scan.nextLine();
driver.findElement(By.xpath("//*[#id='header']/div[3]/form/div/div/input[2]")).sendKeys(my_text);
driver.findElement(ByXPath.xpath("//*[#id='qc-cmp2-ui']/div[2]/div/button[3]")).click();
driver.findElement(ByXPath.xpath("//*[#id='header']/div[3]/form/input[1]")).click();
driver.findElement(ByXPath.xpath("//*[#id='players']/div[1]/div[1]/strong/a")).click();
WebElement element = driver.findElement(By.id("div_per_game"));
List<WebElement> trojke = element.findElements(By.cssSelector("td[data-stat='fg3a_per_g']"));
List<WebElement> sezona = element.findElements(By.xpath("//*[#id='per_game']/tbody/tr/th/a"));
for (WebElement s: sezona)
{
System.out.println(s.getText());
}
for (WebElement t : trojke)
{
System.out.println(t.getText());
}
}
}
I am getting the error message:
NoSuchElementException: no such element: Unable to locate element:
{"method":"xpath","selector":"html/body/form/input[1]"}
when I try running the code below.
And the xpath is correct I already double checked
package Package;
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.firefox.FirefoxDriver;
public class Selenium1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/Html/tryit.asp?filename=tryhtml_checkbox");
WebElement ele =driver.findElement(By.xpath("html/body/form/input[1]"));
boolean displayedstatus = ele.isDisplayed();
System.out.println("The display status :"+displayedstatus);
boolean enablestatus = ele.isEnabled();
System.out.println("The enable status :"+enablestatus);
boolean selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
ele.click();
selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
}
}
Whenever you try searching for the elements within the iframe you must have to switch the focus to the iframe that you are dealing with.
Try this before searching for the elements within the iframe:
driver.switchTo().frame(driver.findElement(By.name("iframeTitle")));
In this case, the iframe Title is : iframeResult
Below is the code:
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.firefox.FirefoxDriver;
public class Selenium1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/Html/tryit.asp?filename=tryhtml_checkbox");
//switching focus to iframe
driver.switchTo().frame(driver.findElement(By.name("iframeResult")));
WebElement ele =driver.findElement(By.xpath("html/body/form/input[1]"));
boolean displayedstatus = ele.isDisplayed();
System.out.println("The display status :"+displayedstatus);
boolean enablestatus = ele.isEnabled();
System.out.println("The enable status :"+enablestatus);
boolean selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
ele.click();
selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
}
}
If you want to handle one of two checkboxes, you need to switch to iframe first and then search for the element.
driver.get("https://www.w3schools.com/Html/tryit.asp?filename=tryhtml_checkbox");
driver.switchTo().frame("iframeResult");
WebElement ele =driver.findElement(By.xpath("//input[#value='Bike']"));
If after that you want to handle elements outside iframe, you might need to switch back with
driver.switchTo().defaultContent();
Need your help wanted to check if particular element is visible or not.
in the below code I have passed wrong ID so that system will throw NoSuchElementException in the case of correct element it is giving correct answer. But in the case of wrong element it is throwing exception instead of handling it.
Please help in this -
package com;
import java.util.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class Windowgoogle {
static WebDriver driver;
static String baseUrl="http:/www.google.co.in";
#Test
public void openBrowser()
{
driver=new FirefoxDriver();
driver.get(baseUrl);
System.out.println(existsElement("qo"));//Adding Invalid ID
}
private boolean existsElement(String id)
{
boolean chk = false;
try {
chk=driver.findElement(By.name(id)).isDisplayed();
return chk;
} catch (NoSuchElementException e)
{
return false;//Control should go to catch but exception is not getting handled properly.
}
}
}
You have imported wrong NoSuchElementException. You should have imported
org.openqa.selenium.NoSuchElementException
instead of java.util.NoSuchElementException
Alternatively, you are able to use driver.findElements as a way to determine if the element is present on the page without using the NoSuchElementException.
For this you would use:
private boolean existsElement(String id) {
return !driver.findElements(By.name(id)).isEmpty();
}
When the method findElements cannot find any elements that match the specified locator, it returns an empty list. It is a very common alternative to catching the NoSuchElementException.
While catching NoSuchElementException works, it's not an elegant solution. Imagine if you have to have this logic in multiple places. The code will be bloated and hard to maintain. You can use helper methods from ExpectedConditions class. This is how you would use it,
WebDriverWait wait = new WebDriverWait(driver,30);
boolean isNotVisible = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("foo")));
if(isNotVisible) {
// do stuff
}
import java.util.NoSuchElementException;
import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class dropdown {
private static WebDriver driver = new FirefoxDriver() ;
String Path ="C:\\Users\\VGupta\\Desktop\\testcases\\auto.xlsx";
#Test
public void test() throws Exception
{
driver.get("http://www.test.com/");
//Dimension size = ('900','500');
driver.manage().window().setSize(new Dimension(1000,1000));
try{
driver.findElement(By.id("foo")).click();
} catch(NoSuchElementException e)
{
System.out.println(e.getStackTrace());
}
}
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebTable_Dynamic {
public static void main(String[] args) {
WebDriver driver= new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.w3schools.com/tags/tag_table.asp");
WebElement element=driver.findElement(By.xpath("//table[#class='reference notranslate']"));
List<WebElement> rows=element.findElements(By.tagName("tr"));
for(int rowNum=1;rowNum<rows.size();rowNum++){
List<WebElement> cells=rows.get(rowNum).findElements(By.tagName("td"));
for(int colNum=0;colNum<cells.size();colNum++){
System.out.print(cells.get(colNum).getText());
System.out.print("----");
}
System.out.println();
}
driver.close();
}
}
My program is extracting the elements from a table.
Currently I am not getting the output in a tabular way due to line break <br> tags in the cell content. Can someone guide me in getting the o/p in a tabular way?
I am trying to fetch data from a web site and I am able to do this but my problem is that
when I fetch data of different commodity from site then I have to change every time in my code and I want to fetch data of following commodity at once how can I achieve my output
commodity
'Rice'
'Jwar'
'Corn'
'Matar'
'Chana'
Here is my code
import com.gargoylesoftware.htmlunit.BrowserVersion;
import java.util.StringTokenizer;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.Select;
public class Getdata1 {
public static void main(String args[]) throws {
int j=0;
WebDriver driver = new HtmlUnitDriver(BrowserVersion.getDefault());
String sDate = "27/03/2014";
String commodity="Jo";
String url="http://www.upmandiparishad.in/commodityWiseAll.aspx";
driver.get(url);
Thread.sleep(5000);
new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddl_commodity"))).selectByVisibleText(commodity);
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txt_rate")).sendKeys(sDate);
Thread.sleep(3000);
driver.findElement(By.id("ctl00_ContentPlaceHolder1_btn_show")).click();
Thread.sleep(5000);
WebElement findElement = driver.findElement(By.id("ctl00_ContentPlaceHolder1_GridView1"));
// WebElement find=driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddl_commodity"));
String htmlTableText = findElement.getText();
htmlTableText=htmlTableText.replace("S.No.DistrictMarketPrice","");
htmlTableText= htmlTableText.replaceAll("\\s(\\d+\\s[A-Z])", "\n$1");
htmlTableText = htmlTableText.replaceAll("(?=(.*?[ ]){4,}).*?[\n\r]", "");
System.out.println(htmlTableText);
driver.close();
driver.quit();
}
}
You perhaps need commodity sent as command line argument or as input from user.