Selinum WebDriver, Java - java

I want to compare three strings getting from three different pages.I am
using below code but unable to proceed. Please check code in the end.Can any
one help me please.
Main problem i am not getting idea how to compare three string from
different pages.
When i have written compare code in if block, getting error "The left-hand
side of an assignment must be a variable"
import java.util.Iterator;
import java.util.List;
import java.util.Set;
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.support.ui.Select;
public class test {
static String Price;
static String InnerPrice;
static String CartPrice;
public static void main (String args[])
{
System.setProperty("webdriver.chrome.driver",
"./Drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.amazon.in/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//input[#id='twotabsearchtextbox']")).
sendKeys("Iphone 7");
driver.findElement(By.xpath("//input[#class='nav-input' and
#value='Go']")).click();
//driver.findElement(By.xpath("//span[#class='a-expander-prompt' and
text()='See more']")).click();
//driver.findElement(By.xpath("//span[#class='a-size-small a-color-base'
and text()='Smartphones & Basic Mobiles']")).click();
try {
Thread.sleep(5000);
} catch (Exception e1) {
System.out.println(e1.getMessage());
}
driver.findElement(By.xpath("//span[contains(text(),'Smartphones')]")).
click();
Select select=new
Select(driver.findElement(By.xpath("//select[#id='sort']")));
select.selectByVisibleText("Price: Low to High");
try {
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Exception is"+e.getMessage());
}
List<WebElement> myElements =
driver.findElements(By.xpath("//span[#class='a-size-base a-color-price s-
price a-text-bold']"));
//System.out.println("Size of List: "+myElements.size());
int size=myElements.size();
for (int i=0;i<size;i++)
{
Price=myElements.get(i).getAttribute("innerText");
System.out.println("Price of Search Result Page is " +Price);
break;
}
myElements.get(0).click();
String parent=driver.getWindowHandle();
// This will return the number of windows opened by Webdriver and will
return Set of St//rings
Set<String>s1=driver.getWindowHandles();
// Now we will iterate using Iterator
Iterator<String> I1= s1.iterator();
while(I1.hasNext())
{
String child_window=I1.next();
// Here we will compare if parent window is not equal to child window then
we will close
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
//System.out.println(driver.switchTo().window(child_window).getTitle());
String
InnerPrice=driver.findElement(By.xpath("//span[#id='priceblock_ourprice']"))
.getText();
System.out.println("Price of Product Details Page is
"+InnerPrice.substring(0,InnerPrice.length()-3));
//To Add product in cart
driver.findElement(By.xpath("//input[#id='add-to-cart-button']")).click();
try {
Thread.sleep(5000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
String CartPrice=driver.findElement(By.xpath("//div[#id='huc-v2-order-row-
inner']//div[#class='a-row a-spacing-micro']//span[starts-with(#style,'text-
decoration:')]")).getText();
System.out.println("Cart Price is "+CartPrice.substring(0,
CartPrice.length()-3));
driver.close();
}
// once all pop up closed now switch to parent window
driver.switchTo().window(parent);
}
If (Price.equalsIgnoreCase(InnerPrice))&&
(InnerPrice.equalsIgnoreCase(CartPrice))
{
System.out.println("Equal");
}
}
}

In the if case, you have
If (Price.equalsIgnoreCase(InnerPrice))&& (InnerPrice.equalsIgnoreCase(CartPrice))
You are closing the if statement too early. No need to put the equalsIgnoreCase method call within braces. Try with
If (Price.equalsIgnoreCase(InnerPrice)&& InnerPrice.equalsIgnoreCase(CartPrice))

Related

Java scripting in Katalon-Studio

I have several java tests that I wrote and used to run them with Eclipse.
I want to import them to katalon and run them.
For example, I have a login script here:
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.*;
public class Login {
public static void main(String args[]) throws IOException {
IOException ioe = new IOException();
//Initializing server
System.setProperty("webdriver.chrome.driver", "C:/selenium/chromedriver.exe");
ChromeDriver wd = new ChromeDriver();
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//login
System.out.println("*** login ***");
wd.get("<URL>");
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<USERNAME>");
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<PASSWORD>");
wd.findElement(By.xpath("//form[#id='form']//paper-button[.='login']")).click();
try { Thread.sleep(3000l); } catch (Exception e) { throw new RuntimeException(e); }
if(wd.findElement(By.tagName("html")).getText().contains("please login")){
System.out.println("Login failed");
throw ioe;
}//End of login
System.out.println("Login was executed successfully!");
System.out.println("Testcase finished successfully!");
wd.quit();
}
}
I want to run it as is in katalon but I'm not sure how.
Thanks.
I try adding the existing java script without declaring class and main method and it work.
In your example, please remove: import org.openqa.selenium.*; , replace it with: import org.openqa.selenium.By then paste the remain script without
public class Login {
public static void main(String args[]) throws IOException {
}}
So your custom test case in Katalon would be:
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
IOException ioe = new IOException();
//Initializing server
System.setProperty("webdriver.chrome.driver", "C:/selenium/chromedriver.exe");
ChromeDriver wd = new ChromeDriver();
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//login
System.out.println("*** login ***");
wd.get("<URL>");
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<USERNAME>");
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<PASSWORD>");
wd.findElement(By.xpath("//form[#id='form']//paper-button[.='login']")).click();
try { Thread.sleep(3000l); } catch (Exception e) { throw new RuntimeException(e); }
if(wd.findElement(By.tagName("html")).getText().contains("please login")){
System.out.println("Login failed");
throw ioe;
}//End of login
System.out.println("Login was executed successfully!");
System.out.println("Testcase finished successfully!");
wd.quit();

Selenium webdriver xpath randomly not recognized

When running the code appears that the XPath for the Aprobă button isn't recognized and doesn't click on it even if when I inspect the element on the site the XPath seems to find the correct button.
The error is:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element {"method":"xpath","selector":"//a[contains(.,'')]/ancestor::div[contains(#class, 'js-answer-element')]//span[#class='sg-icon-as-button__hole']"}
My method approveAnswerByUsername(String username) should check if the answer has been approved or not. An approved answer is recognized by the 3 buttons near the username and the green circle under it.
The user can be the first one that answers, the second one or the only one. That's why I used "ancestor" in the XPath.
In some cases, the circles have been seen(even in the precedent case it was) and in others not. The same with the button "Aprobă".
The code below should do the following:
1. connect to the www.brainly.ro and login with the credentials
2. open the window of the user Lola1511
3. open all the answered questions and check if it has been approved or not. If isn't approved, then approve it.
Below I post my entire code (the link to the site and the credentials are all there)
import java.util.ArrayList;
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.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class classTest {
WebDriver driver;
#BeforeTest
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\sanduc\\Desktop\\Selenium\\Kits\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.get("");
} catch (Exception e) {
e.printStackTrace();
}
}
#Test(priority = 1)
public void log_in() {
try {
driver.findElement(
By.xpath("//div[#class='sg-content-box__actions']/nav[#class='brn-hero__navigation']/a[1]"))
.click();
driver.findElement(By.xpath("//form[#action='/login?entry=2&return=/']/div[2]/input"))
.sendKeys("my_emal#mail.com");
driver.findElement(By.xpath("//form[#action='/login?entry=2&return=/']/div[3]/input"))
.sendKeys("my_password");
driver.findElement(By.xpath("//button[#type='submit']")).click();
Thread.sleep(4000);
driver.get("");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Test(priority = 2)
public void click_pages() {
try {
int index_while = 1;
while (true) {
driver.get("" + index_while);
List<WebElement> demovar = driver.findElements(By.xpath("//div[#class='task-content']/a"));
System.out.println(demovar.size());
System.out.println("+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+");
System.out.println("Current page: " + driver.getCurrentUrl());
System.out.println("+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+");
ArrayList<String> hrefs = new ArrayList<String>(); // List for
// storing
// all href
// values
// for 'a'
// tag
for (WebElement var : demovar) {
System.out.println(var.getText()); // used to get text
// present between the
// anchor tags
System.out.println(var.getAttribute("href"));
hrefs.add(var.getAttribute("href"));
System.out.println("*************************************");
}
// Navigating to each link
int i = 0;
for (String href : hrefs) {
driver.navigate().to(href);
System.out.println((++i) + ": navigated to URL with href: " + href);
approveAnswerByUsername("Lola1511");
Thread.sleep(3000); // To check if the navigation is
// happening properly.
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
index_while++;
if (demovar.size() < 5) {
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void approveAnswerByUsername(String username) {
try {
if (driver.findElement(By.xpath("//a[contains(.,'" + username
+ "')]/ancestor::div[contains(#class, 'js-answer-element')]//span[#class='sg-icon-as-button__hole']")).isDisplayed()) {
System.out.println("The homework " + driver.getCurrentUrl() + " has ALREADY been approved");
} else {
driver.findElement(By.xpath("//a[contains(.,'" + username
+ "')]/ancestor::div[contains(#class, 'js-answer-element')]//div[contains(#class,'js-approve-button-text')][contains(.,'Aprobă')]")).click();
Thread.sleep(2000);
driver.navigate().refresh();
System.out.println("The homework " + driver.getCurrentUrl() + " has been approved NOW");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I couldn't check the code due to time limitations but I would suggest a different approach for using selectors.
Use ID selectors or name selectors in the webpage instead of xpaths.
ID selectors are the best and fastest way for selecting elements. Xpaths are slower and sometimes unreliable.
My advice would be to try ID and name selectors and use xpath only if both are not found.

How to upload Multiple files in selenium?

I'm trying to use following code :-
driver.findElement(By.xpath(".//*[#id='attach0']")).sendKeys("first path"+"\n"+"second path""+"\n"third path");
I didn't get result.
you can use AutoIT or JAVA code. Below i have used both for your reference. Try anyone of them
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
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;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AutoITforUpload {
private static WebDriver driver;
private static WebDriverWait waitForElement;
#FindBy(css = "span.btn.btn-success.fileinput-button")
private WebElement Add_files_btn;
#BeforeClass
public static void setUp() {
DesiredCapabilities desicap = new DesiredCapabilities();
System.setProperty("webdriver.chrome.driver", "D:/WorkSpace/Driver/chromedriver.exe");
desicap = DesiredCapabilities.chrome();
driver = new ChromeDriver(desicap);
driver.manage().window().maximize();
driver.get("https://blueimp.github.io/jQuery-File-Upload/");
waitForElement = new WebDriverWait(driver, 30);
}
#Test
public void AutoitUpload() {
// String filepath =
// "D:/Mine/GitHub/BasicProgramLearn/AutoItScript/unnamed.png";
WebElement btn = driver.findElement(By.cssSelector("span.btn.btn-success.fileinput-button"));
String file_dir = System.getProperty("user.dir");
String cmd = file_dir + "\\AutoItScript\\unnamed.png";
System.out.println("File directory is " + file_dir);
try {
// Using ordinary
Thread.sleep(3000);
for(int i=0;i<3;i++) //multiple times upload ;
driver.findElement(By.xpath("//*[#id='fileupload']/div/div[1]/span[1]/input")).sendKeys(cmd);
//use any String Array for multiple files
waitForElement(btn);
btn.click();
Thread.sleep(3000);
System.out.println(file_dir + "/AutoItScript/FileUploadCode.exe");
Runtime.getRuntime().exec(file_dir + "\\AutoItScript\\ChromeFileUpload.exe" + " " + cmd);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
#AfterClass
public static void TearDown() {
try {
Thread.sleep(5000);
driver.quit();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void waitForElement(WebElement vElement) {
waitForElement.until(ExpectedConditions.visibilityOf(vElement));
}
}
The code in AutoIt is
#include<IE.au3>
If $CmdLine[0] < 2 Then
$window_name="Open"
WinWait($window_name)
ControlFocus($window_name,"","Edit1")
ControlSetText($window_name,"","Edit1",$CmdLine[1])
ControlClick($window_name,"","Button1")
EndIf
Hope this gives you an idea

How to do web scraping using htmlunitsriver?

i am getting somthing like this
Hi i am scraping a web page using Selenium Webdriver an i am able to achieve my data but problem is that this directly interact with browser and i dont want to open a web browser and want to scrape all data as it is
How can i achieve my goal
Here is my code
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 GetData {
public static void main(String args[]) throws InterruptedException {
String sDate = "27/03/2014";
WebDriver driver = new FirefoxDriver();
String url="http://www.upmandiparishad.in/commodityWiseAll.aspx";
driver.get(url);
Thread.sleep(5000);
// select barge
new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddl_commodity"))).selectByVisibleText("Jo");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txt_rate")).sendKeys(sDate);
// click buttonctl00_ContentPlaceHolder1_txt_rate
Thread.sleep(3000);
driver.findElement(By.id("ctl00_ContentPlaceHolder1_btn_show")).click();
Thread.sleep(5000);
//get only table tex
WebElement findElement = driver.findElement(By.id("ctl00_ContentPlaceHolder1_GridView1"));
String htmlTableText = findElement.getText();
// do whatever you want now, This is raw table values.
System.out.println(htmlTableText);
driver.close();
driver.quit();
}
}
My updated New code
import com.gargoylesoftware.htmlunit.BrowserVersion;
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 InterruptedException {
WebDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
driver.get("http://www.upmandiparishad.in/commodityWiseAll.aspx");
System.out.println(driver.getPageSource());
Thread.sleep(5000);
// select barge
new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddl_commodity"))).selectByVisibleText("Jo");
String sDate = "12/04/2014"; //What date you want
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txt_rate")).sendKeys(sDate);
driver.findElement(By.id("ctl00_ContentPlaceHolder1_btn_show")).click();
Thread.sleep(3000);
//get only table tex
WebElement findElement = driver.findElement(By.id("ctl00_ContentPlaceHolder1_GridView1"));
String htmlTableText = findElement.getText();
// do whatever you want now, This is raw table values.
System.out.println(htmlTableText);
driver.close();
driver.quit();
}
}
Thanks in advance
Use HtmlUnit or HtmlUnitDriver by Selenium
WebDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_17);
driver.get("http://www.upmandiparishad.in/commodityWiseAll.aspx");
System.out.println(driver.getPageSource());
Thread.sleep(5000);
// select barge
new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddl_commodity"))).selectByVisibleText("Jo");
String sDate = "12/04/2014"; //What date you want
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txt_rate")).sendKeys(sDate);
driver.findElement(By.id("ctl00_ContentPlaceHolder1_btn_show")).click();
Thread.sleep(3000);
//get only table tex
WebElement findElement = driver.findElement(By.id("ctl00_ContentPlaceHolder1_GridView1"));
String htmlTableText = findElement.getText();
// do whatever you want now, This is raw table values.
System.out.println(htmlTableText);
driver.close();
driver.quit();
To get tabular output, you can try something like this..
String arrCells[] = htmlTableText.split(" ");
Boolean bIsANumber = false;
for(int i = 0; i < arrCells.length; i++) {
try {
int tmp = Integer.parseInt(arrCells[i]);
bIsANumber = true;
}
catch(Exception ex) {
bIsANumber = false;
}
if(bIsANumber) {
System.out.print("\n"+arrCells[i]+"\t");
}
else {
System.out.print(arrCells[i]+"\t");
}
}

Selenium webdriver : <WebElement> Iterator cannot be resolved to a type

My Problem in brief :
Through My selenium web driver right now i am testing list of elements in a list box , While using the following code i am getting the error
Testing Configuration :
Mozilla firefox
Eclipse Indigo
Selenium Webdriver 2
Scenario which i tested :
Open website
Select and display the list box items
Write to console
My error :
java.lang.Error: Unresolved compilation problems: The type List is not generic; it cannot be parameterized with arguments Iterator cannot be resolved to a type
My Code :
package com.example.tests;
import java.util.Iterator;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.WebElement;
import org.openqa.jetty.html.List;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import com.browsersetup.test.BrowserSetup;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.annotations.Test;
#SuppressWarnings("unused")
public class sample2 extends BrowserSetup{
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass
public void setUp() throws Exception {
driver = new OperaDriver();
baseUrl = "http://www.ebay.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println("Browser = " + driver);
System.out.println("Base URL = " + baseUrl);
}
#Test
public void testUntitled() throws Exception {
driver.get(baseUrl + "/");
Thread.sleep(10000);
WebElement element = driver.findElement(By.name("_sacat"));
Select dd= new Select(element);
List<WebElement> allOptions= dd.getOptions();
//To go through the list, we can use an Iterator.
//Iterator should be of the same type as the List
//which is WebElement in this case.
Iterator<WebElement> it = allOptions.iterator();
//Using while loop, we can iterate till the List has
//a next WebElement [hasNext() is true]
//number of items in the list
System.out.println(allOptions.size());
while(it.hasNext()){
//When you say it.next(), it points to a particular
//WebElement in the List.
WebElement el = it.next();
//Check for the required element by Text and click it
if(el.getText().equals("mango")){
System.out.println(el.getAttribute("value"));
el.click();
}
}
#AfterClass
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
I dont know where it went wrong,guide me where it went wrong
thanks in advance
See the javadocs of org.openqa.jetty.html.List: http://www.jarvana.com/jarvana/view/org/seleniumhq/selenium/selenium-server/2.0b1/selenium-server-2.0b1-javadoc.jar!/org/openqa/jetty/html/List.html
and the one of the java.util.List: http://docs.oracle.com/javase/7/docs/api/java/util/List.html
The one you used doesn't support generics (as the error says).
The problem in your case seems to be the following import:
import org.openqa.jetty.html.List;
try to replace it with:
import java.util.List;
For more ideas see similar question: The type Collection is not generic; it cannot be parameterized with arguments <? extends E>

Categories