How to print some text side by side using Selenium? - selenium-webdriver

I have to print the hotel name and price side by side
example: oyo Rooms - 2000rs
I tried to use the Selenium web driver.
WebDriver driver = new ChromeDriver();
String baseUrl = "https:www.teletextholidays.co.uk";
driver.get(baseUrl);
driver.manage().window().maximize();
WebElement all_Inclusive = driver.findElement(By.xpath("//*[#class='header pstn-fxd edge txt-center fixed-nav-container']//div[#class='show-on-desktop inblock']//a[#class='top-nav-allinclusive nav-item txt-white inblock hover-out allinclusivelink']"));
all_Inclusive.click(); WebElement all_hotels =driver.findElement(By.xpath("//*[#class='lg-flex-box']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();", all_hotels);
List<WebElement> hotellist = driver.findElements(By.xpath("//*[#class='deal-price pstn-reltv grid-stay items-center space-between']//span[#class='dstn-name txt-bold']"));
System.out.println(hotellist.get);
List<WebElement> pricelist = driver.findElements(By.xpath("//*[#class='deal-price pstn-reltv grid-stay items-center space-between']//span[#class='tth-price font-bold txt-sunset']" ));
/*for (WebElement hotel : hotellist) {
System.out.println(hotel.getText());
}*/
for (WebElement price : pricelist) {
System.out.println(price.getText());
if(price.getText().contains("157")) {
System.out.println(hotel);
}
}
Expected output: Oyo - 1000, alpha - 2345.
What am I doing wrongly?

We need to fetch parent elements first and then find hotel and price from that elements to keep co-relation b/w them.
Try the following code to print hotel - price format.
List<WebElement> listOfLinks = driver.findElements(By.cssSelector("a>div.deal-price"));
for(WebElement link: listOfLinks) {
System.out.print(link.findElement(By.cssSelector(".from-price>.dstn-name")).getText());
System.out.print(" - ");
System.out.println(link.findElement(By.cssSelector(".txt-right .tth-price")).getText());
}

Related

Count Of Hidden Rows in WebTable By Using Selenium

I have a hide button in the application that hides duplicate data entries on web table. I have been trying to capture the number of hidden rows. See html and my approaches below. Every attempt I have tried ended up with 0. However, the result should be 2.
HTML CODE:
<tbody>
<tr role = "row" class="odd">...<tr/>
<tr role = "row" class="even">...<tr/>
<tr role = "row" class="odd">...<tr/>
<tr role = "row" class="even">...<tr/>
<tr role = "row" class="odd">...<tr/>
<tr role = "row" class="odd duplicate" style="display: none;" >...<tr/>
<tr role = "row" class="even duplicate" style="display: none;" >...<tr/>
</tbody>
def getInvisibleTableRowCount()
{
WebDriver driver = DriverFactory.getWebDriver()
WebElement table = driver.findElement(By.xpath("//*[#id='DataTables_Table_0']/tbody"))
List<WebElement> rows_table= table.findElements(By.cssSelector("[display=none]"));
int rowSize = rows_table.size();
return rowSize;
}
Here is my other attempt:
def getInvisibleTableRowCount()
{
WebDriver driver = DriverFactory.getWebDriver()
WebElement table = driver.findElement(By.xpath("//*[#id='DataTables_Table_0']/tbody"))
List<WebElement> rows_table= table.findElements(By.tagName("tr[not(contains(#style,'display: none;'))]"));
int rowSize = rows_table.size();
return rowSize;
}
If I ran the xpath as //*[#id='DataTables_Table_0']/tbody/tr[not(contains(#style,'display: none;'))] , I can find the hidden rows on the browser.
I have also tried this:
def getInvisibleTableRowCount()
{
WebDriver driver = DriverFactory.getWebDriver()
WebElement table = driver.findElement(By.xpath("//*[#id='DataTables_Table_0']/tbody"))
List<WebElement> rows_table= table.findElements(By.tagName("tr"));
int rowSize = rows_table.size();
for(WebElement row: rows_table)
{
if(row.isDisplayed()==false)
{
rowSize = rowSize -1;
}
}
return rowSize;
}
After #Hac's comment, I tried JQuery. I ran the jQuery on browser, it works with no problem. But I get a "NULL" value returned in my function. I double checked the jQuery string that prompts correct in the comment line.
#Keyword
def getTableRowCountAfterHiding()
{
def jQuery='$'+'("#DataTables_Table_0 tbody tr:visible").length'
WebUI.comment(jQuery);
def visibleRowCounts = new utils.ExecuteJavaScript().executeJavaScript(jQuery);
return visibleRowCounts;
}
I defined utils to run JS as it is in below:
public class ExecuteJavaScript {
//This keyword is designed to execute JS.
#Keyword
def executeJavaScript(String javascript) {
((JavascriptExecutor) DriverFactory.getWebDriver()).executeScript(javascript)
}
}
This worked:
def getTableRowCountAfterHiding()
{
WebDriver driver = DriverFactory.getWebDriver()
List<WebElement> table = driver.findElements(By.xpath("//*[#id='DataTables_Table_0']/tbody/tr[not(contains(#style,'display: none;'))]"))
int rowSize = table.size();
return rowSize;
}

Displaying Blank page in which PDF link is included

Android OS version 7.1.1, following code display blank screen first time after download the App. Have to kill the App and open it again to work normally. Please advise.
Code:
Container cc = new Container(BoxLayout.y());
cc.setScrollableY(true);
TextArea ta = new TextArea(Util.readToString(is));
ta.setEditable(false);
ta.setUIID("Label");
Button b = new Button("Terms of Service");
b.addActionListener(e3 -> {
try {
FileSystemStorage fs = FileSystemStorage.getInstance();
final String homePath = fs.getAppHomePath();
String fileName = homePath + "Terms of Service.pdf";
Util.copy(Display.getInstance().getResourceAsStream(getClass(), "/Terms of Service.pdf"), fs.openOutputStream(fileName));
Display.getInstance().execute(fileName);
} catch (IOException ex) {
}
});
cc.add(ta);
CheckBox rememberMe1 = new CheckBox();
rememberMe1.setSelected(false);
rememberMe1.setHeight(Display.getInstance().convertToPixels(10.0f));
rememberMe1.setAutoSizeMode(true);
b.setAutoSizeMode(true);
setSameHeight(rememberMe1, l11, b);
cc.add(FlowLayout.encloseIn(rememberMe1, b));

How to switch to Iframe in selenium

I am finding difficult to enter the user name and password present on the iframe which gets popped up when we click on the signin link.
Can somebody help me on this.
Site link given below
link : http://cashkaro.iamsavings.co.uk/
With Regards,
There is a predefined method exists in Selenium which you can use to switch to a Frame or an IFrame.
WebDriver driver = new FirefoxDriver();
There are 3 overloaded methods which you can use to switch to a frame.
1. driver.switchTo().frame(String frameId);
2. driver.switchTo().frame(int frameNumber);
3. driver.switchTo().frame(WebElement frame);
You can either of the above 3 methods to switch on a frame.
Hope it helps!
For the switch to an iframe, you can use:
public void switchToFrame(WebElement element) {
getDriver().switchTo().frame(element);
}
or
wati.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By locator)
wati.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(WebElement element)
To work with iframe you must switch from your current page to iframe.
Try the below code and let me know your result.
WebDriver driver = new FirefoxDriver();
driver.get("http://cashkaro.iamsavings.co.uk/");
String linkText = "SIGN IN";
WebElement eventElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.linkText(linkText)));
eventElement.click();
WebElement frame = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[14]/div[1]/div[2]/div[2]/div[1]/iframe")));
driver.switchTo().frame(frame);
driver.findElement(By.id("uname")).sendKeys("username#domain.com");
driver.findElement(By.id("uname")).sendKeys(Keys.TAB);
driver.findElement(By.id("pwd")).sendKeys("enteryourpassword");
driver.findElement(By.id("sign_in")).click();
Use your valid login credentials to sign in.
Please find the answer below
public void login_normally() {
navigate_to_url(prop.getProperty("url_prod_Locale"));
// Parent window
String parent_window = driver.getWindowHandle();
System.out.println("Parent windiow :" + parent_window);
driver.findElement(By.xpath(prop.getProperty("singin_link"))).click();
WebDriverWait wait = new WebDriverWait(driver, 7);
String iframe_xpath = prop.getProperty("iframe_com_xpath");
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
.xpath(iframe_xpath)));
driver.findElement(By.xpath(prop.getProperty("email_id_InSignIn")))
.sendKeys(prop.getProperty("user_email_id_signIn"));
driver.findElement(By.cssSelector(prop.getProperty("password_InSign")))
.sendKeys(prop.getProperty("pwd_signIn"));
boolean check_box_flag = driver.findElement(
By.xpath(prop.getProperty("Keep_me_signed_in"))).isSelected();
System.out.println("check_box_flag" + check_box_flag);
if (check_box_flag == false) {
driver.findElement(By.xpath(prop.getProperty("Keep_me_signed_in")))
.click();
}
driver.findElement(By.xpath(prop.getProperty("sign_button_signIn")))
.click();
//=================================================================================
/* String login_mesg_error = driver.findElement(
By.cssSelector(prop.getProperty("loginerror"))).getText();
System.out.println(" login Error : " + login_mesg_error);
if (login_mesg_error.length()<0 ) {
System.out.println("Sucessfully Loggedin");
Assert.assertTrue(true, "Sucessfull Login");
APPLICATION_LOG.debug(login_mesg_error);
} else {
System.out.println("Login Failed");
Assert.assertTrue(false, login_mesg_error);
APPLICATION_LOG.debug(login_mesg_error);
}*/
//==============================================================================
String login_mesg_error=" ";
List<WebElement> li=driver.findElements(By.cssSelector(prop.getProperty("logout_button_css")));
System.out.println(" list size :" +li.size());
if(li.size()>0)
{
System.out.println("Sucessfully Loggedin");
Assert.assertTrue(true, "Sucessfull Login");
APPLICATION_LOG.debug("Sucessfull Login");
} else {
login_mesg_error = driver.findElement(
By.xpath(prop.getProperty("login_error_mesg"))).getText();
System.out.println(" login Error : " + login_mesg_error);
System.out.println("Login Failed");
Assert.assertTrue(false, "Login failed - Incorrect username or password");
APPLICATION_LOG.debug(login_mesg_error + "Login failed");
}
driver.switchTo().defaultContent();
}

How to skip the locator which does not exist in selenium webdriver?

I have around 50 rows in a page. But those items are in sequence.
The problem is when someone entered and deleted that table row. That id would not be there in page..
Example:
User added 1st record: id 101 added.
User added 2nd record: id 102 added
User added 3rd record: id 103 added.
If user deletes 2nd record, then two records would be there on the page but with id 101, 103.
I am trying to write that if that id is present then get the text else leave that in the for loop. I am getting only records till it found if that id is not found getting NoSuchElementException is displayed.
Please correct the code. But i want to the solution that if that id not exist, skip and run the else part.
for (int i = counterstart; i <= counterend; i++) {
if(driver.findElement(By.xpath("//*[#id='" + i + "']/a")).isDisplayed()){
System.out.println(i+" is present");
String Projects = driver.findElement(By.xpath("//*[#id='" + i + "']/a")).getText();
System.out.println(Projects);
} else{
System.out.println(i+" is NOT present");
}
}
The exception that I get:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == //*[#id='7593']/a (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 503 milliseconds
Try this method isPresent instead of isDisplayed.
public boolean isPresent(WebElement e) {
boolean flag = true;
try {
e.isDisplayed();
flag = true;
}
catch (Exception e) {
flag = false;
}
return flag;
}
How about this:
for (int i = counterstart; i <= counterend; i++) {
WebElement element;
try{
element = driver.findElement(By.xpath("//*[#id='" + i + "']/a"));
}catch(NoSuchElementException n)
{
element = null;
}
if(element !=null){
System.out.println(i+" is present");
String Projects = driver.findElement(By.xpath("//*[#id='" + i + "']/a")).getText();
System.out.println(Projects);
}else{
System.out.println(i+" is NOT present");
}
}
Find all the parent of all the elements you want to get the text from and use it to drill down, this way you won't get the exception
Assuming the html looks like this
<div id="parent">
<div id="11">
<a>text</a>
</div>
<div id="12">
<a>text</a>
</div>
<div id="13">
<a>text</a>
</div>
</div>
You can do this
// get all the elements with id
List<WebElement> ids = driver.findElements(By.cssSelector("#parent > div"));
// get all the texts using the id elements
for (WebElement id :ids) {
String projects = id.findElement(By.tagName("a")).getText();
System.out.println(projects);
}

Values are not displaying in UserInterface using Web Driver

I am new in Selenium webdriver.When i reading values from Excel sheet and saved to database.The values are not displaying in the webpage and also not inserted to Database.
Here this is my code for one form.If there any way for solving this issue.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.chrome.ChromeDriver;
public class DeliveryNote
{
public static void main(String[] args) throws InterruptedException, BiffException, IOException
{
//For ChromeBrowser
//System.setProperty("webdriver.chrome.driver", "E:/Softwares/Chrome/Chromedriver.exe");
//WebDriver driver = new ChromeDriver();
WebDriver driver = new FirefoxDriver();
//Puts a Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://192.168.1.185:8080/Nayonika/loginPage.html");
//Maximize the browser
driver.manage().window().maximize();
// xpath of username
driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/p[1]/input")).sendKeys("aaa");
// xpath of password
driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/p[2]/input")).sendKeys("2222");
//xpath of checkbox
driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/p[3]/label/input")).click();
//xpath of login button
driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/p[4]/input")).click();
System.out.println(" Login Successfully.....");
//Puts a Implicit wait, Will wait for 20 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Navigate to sales
Actions actions = new Actions(driver);
//Xpath of Documents
WebElement Mainmenu = driver.findElement(By.xpath("/html/body/div[2]/div/div[1]/ul/ul/li[1]/a"));
//xpath of Sales
WebElement Submenu = driver.findElement(By.xpath("/html/body/div[2]/div/div[1]/ul/ul/li[1]/ul/li[2]/a"));
//xpath of Delivery Note
WebElement Childsubmenu = driver.findElement(By.xpath("/html/body/div[2]/div/div[1]/ul/ul/li[1]/ul/li[2]/ul/li[5]/a"));
actions.moveToElement(Mainmenu).moveToElement(Submenu).moveToElement(Childsubmenu).click().build().perform();
Thread.sleep(5000);
//Specify the file path of the excelsheet
FileInputStream fi = new FileInputStream("D:\\7SYSERP\\deliverynote.xls");
Workbook W = Workbook.getWorkbook(fi);
//TO get the access to the sheet
Sheet s = W.getSheet(0);
// xpath of New Button
driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[2]/tr[2]/td/input[1]")).click();
for(int i = 4; i<= 5;i++)
{
// xpath of New Button
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[2]/tr[2]/td/input[1 ")).click();
//Puts a Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//xpath of StockDetail id
String stkdtlid = s.getCell(0,i).getContents();
System.out.println("StockDetail id" + stkdtlid);
// driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[1]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[1]/input")).sendKeys(stkdtlid);
//driver.findElement(By.id("1196")).clear();
driver.findElement(By.id("1196")).sendKeys(stkdtlid);
System.out.println("StockDetail id1" + stkdtlid);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//xpath of Delivery Note Detail Remarks
String remarks = s.getCell(1,i).getContents();
System.out.println("Delivery Note Detail Remarks" +remarks);
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[2]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[2]/input")).sendKeys(remarks);
//driver.findElement(By.id("287")).clear();
driver.findElement(By.id("287")).sendKeys(remarks);
System.out.println("Delivery Note Detail Remarks 1" +remarks);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// xpath of Delivery Note Details Status id
String delntdtlstatusid = s.getCell(2,i).getContents();
System.out.println("Delivery Note Details Status id" +delntdtlstatusid);
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[3]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[3]/input")).sendKeys(delntdtlstatusid);
//driver.findElement(By.id("286")).clear();
driver.findElement(By.id("286")).sendKeys(delntdtlstatusid);
System.out.println("Delivery Note Details Status id 1" +delntdtlstatusid);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//xpath of Quantity
String qty = s.getCell(3,i).getContents();
System.out.println("Quantity " +qty );
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[4]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[4]/input")).sendKeys(qty );
//driver.findElement(By.id("285")).clear();
driver.findElement(By.id("285")).sendKeys(qty);
System.out.println("Quantity 1" +qty );
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//xpath of Unit id
String untitid = s.getCell(4,i).getContents();
System.out.println("Unit id" +untitid);
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[5]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[5]/input")).sendKeys(untitid);
//driver.findElement(By.id("284")).clear();
driver.findElement(By.id("284")).sendKeys(untitid);
System.out.println("Unit id 1" +untitid);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//xpath of Item id
String itemid = s.getCell(5,i).getContents();
System.out.println("Item id " + itemid);
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[6]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[6]/input")).sendKeys(itemid);
//driver.findElement(By.id("283")).clear();
driver.findElement(By.id("283")).sendKeys(itemid);
System.out.println("Item id 1 " + itemid);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// xpath of Delivery Note id
String delvrynteid = s.getCell(6,i).getContents();
System.out.println("Delivery Note id" +delvrynteid);
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[7]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[7]/input")).sendKeys(delvrynteid);
//driver.findElement(By.id("282")).clear();
driver.findElement(By.id("282")).sendKeys(delvrynteid);
System.out.println("Delivery Note id 1" +delvrynteid);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// xpath of Delivery Note Detail id
String delvryntedtlid = s.getCell(7,i).getContents();
System.out.println("Delivery Note Detail id " +delvryntedtlid);
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[8]/input")).clear();
//driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[8]/input")).sendKeys(delvryntedtlid);
//driver.findElement(By.id("281")).clear();
driver.findElement(By.id("281")).sendKeys(delvryntedtlid);
System.out.println("Delivery Note Detail id 1 " +delvryntedtlid);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// xpath of Save
driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div/div/table[1]/tr[2]/td[9]/input[1]")).click();
System.out.println("Saved");
}
driver.close();
}
}

Resources