I've a quick question...well what I hope will be a quick questions.
I have a div element which looks like the following:
<div class="slideshow-image" data-thumb-index="0" data-interchange="
[//someURL/5/568/1_40.jpg, (default)],
[//someURL/5/568/1_40.jpg, (small)],
[//someURL/5/568/1_70.jpg, (medium)],
[//someURL/5/568/1_base.jpg, (large)]
" data-uuid="interchange-i9a0pkp20" style="min-height: 527px; background-image: url(http://someURL/5/568/1_base.jpg);">
<div class="pageheader-overlay"></div></div>
Now through webdriver I want to get each of the URL's in the data-interchange. However I've zero idea how to get this out...can anyone out there help?
Thanks,
Phil
Here is an example based on the following conditions:
1) div will be searched by its classname
2) the result string is split into pieces by the comma
3) the split strings are checked if they end with "jpg" - if so, some formatting and trimming is made
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Selenium2Example {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
// local test URL
driver.get("http://localhost:8080");
WebElement element = driver.findElement(By.className("slideshow-image"));
String attribute = element.getAttribute("data-interchange");
String[] urls = attribute.split(",");
for (String url : urls) {
if (url.endsWith("jpg")) {
System.out.println("URL Info: " + url.replace("[", "").trim());
}
}
// Close the browser
driver.quit();
}
}
Related
I have to automate the Flight page for the below URL
URL: https://www.cheapoair.com/deals/business-class-airfares
Enter LAS in the 'Flying From ' Textbox and you will see the list getting displayed and have to select the First Airport code from the auto-populated list matching the Airport Code .
I have to automate using Selenium with java. Could you share the piece of code for it.
Flight image with Autopopulated origin List
Given this select:
<select name="airports" id="airport">
<option value="lax">Los Angeles</option >
<option value="sfo">San Francisco</option >
<option value="pdx">Portland</option >
</select>
...you can select by label text:
Select select = new Select(driver.findElement(By.name("airports")));
select.selectByVisibleText("Portland");
...or by value:
Select select = new Select(driver.findElement(By.name("airports")));
select.selectByValue("pdx");
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.expedia.co.in/Flights");
WebElement textbox=driver.findElement(By.xpath("//input[#id='flight-origin']"));
textbox.clear();
textbox.sendKeys("LAS");
Thread.sleep(4000);
List<WebElement> allOptions = driver.findElements(By.xpath("//div[#id='typeahead-list']"));
int count=allOptions.size();
System.out.println("No of autosuggestions"+count);
for(int i=0;i<count;i++)
{
String text=allOptions.get(i).getText();
System.out.println(text);
}
textbox.sendKeys(Keys.ARROW_DOWN);
textbox.sendKeys(Keys.ENTER);
}
}
Hi please find the solution to above problem
package com.daythree;
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.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExpediaProblem {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "F:\\workspace\\...\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.navigate().to("https://www.expedia.co.in/Flights");
driver.findElement(By.id("flight-origin")).click();
// Thread.sleep(3000);
driver.findElement(By.id("flight-origin")).sendKeys("las");
// wait for the suggestions to appear
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[#role='listbox']/div/li/a/div/div"))));
List<WebElement> suggestions = driver.findElements(By.xpath("//*[#role='listbox']/div/li/a/div/div"));
System.out.println("Size of the suggestions is : " + suggestions);
String val = "Las Vegas, NV, US";
for(int i=0;i<suggestions.size();i++){
// this will print all the suggestions
System.out.println("value is : " + suggestions.get(i).getText());
// now logic to select the option
if(suggestions.get(i).getText().contains(val)){
suggestions.get(i).click();
break;
}
}
}
}
I am trying to find the subheading text: "You can join this team without approval if you have a farzanshaikh.com email address."
Although this text is present in the page source, it always returns false for .contains()
Code:
package JUnitTesting;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestOne {
WebDriver driver;
String BaseUrl;
String TeamDomain = "farzanshaikh.com";
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Automation\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
BaseUrl = "http://farzanshaikh.flock.co/";
driver.get(BaseUrl);
driver.manage().window().maximize();
}
#Test
public void test() {
String element = driver.getPageSource();
System.out.println(element);
if(driver.getPageSource().contains("You can join this team without approval if you have a "+TeamDomain+" email address.")){
System.out.println("The Sub Heading on the Team URL page is Correct");
}
else{
System.err.println("The Sub Heading on the Team URL page is Wrong.");
}
}
#After
public void tearDown() throws Exception {
Thread.sleep(2000);
driver.quit();
}
}
Well, I don't see any issue either in your code or in the result.
Manually when we look into the webpage we can see the text You can join this team without approval if you have a farzanshaikh.com email address.
But when we try to get the pagesource the part of the string cotaining the text reads like: You can join this team without approval if you have a <span class='domains-list'>{{canJoinDomains}}</span> email address.
Finally, you are trying to use contains to validate if the first string is present in the second string. Hence it fails. If you can reduce the first string to something like You can join this team without approval, it would return True.
Let me know if this answers your question.
Below is the HTML Query.
<div id="dvCount" style="">
<span>Total Log Count : </span>
<span id="spnLogCount">46</span>
</div>
I want to print the value 46 in Selenium WebDriver. Please let me know the code.
I am using the following code but I am unable to get the value:
WebElement Text= driver.Findelement(By.cssselector(xpath).gettext();
system.out.println("total" + Text);
But this code is not working. How do I properly get to the value in the "spnLogCount" tag?
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/rajnish/Desktop/my.html");
// way one
// you can create your custom x path
// one x path can be made directly using id of the span like
// xpath = //span[#id='spnLogCount']
// also not if you are not sure of the tag name then you can also use * in xpath like below
String myText = driver.findElement(By.xpath("//*[#id='dvCount']/span[2]")).getText();
System.out.println("Total Log Count : " + myText);
// way two
// you can directly use id
myText = driver.findElement(By.id("spnLogCount")).getText();
System.out.println("Total Log Count : " + myText);
// way three
// if you are using css selector then for id you can use #
myText = driver.findElement(By.cssSelector("#spnLogCount")).getText();
System.out.println("Total Log Count : " + myText);
}
UPDATE
driver.findElement(By.id("ui-id-3")).click();
driver.findElement(By.linkText("Info Log")).click();
driver.findElement(By.id("txtMessage")).sendKeys("Push Success");
driver.findElement(By.id("txtMachineName")).sendKeys("AC204");
driver.findElement(By.id("txtPortal")).sendKeys("91");
driver.findElement(By.id("btnSearch")).click();
// use it just before the sendkeys code like this
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='dvCount']/span[2]")));
String text = driver.findElement(By.xpath("//*[#id='dvCount']/span[2]")).getText();
System.out.println(text);
Hope this helps
I think you want something like this:
WebElement textElement = driver.findElement(By.xpath(".//div/span"));
String text = textElement.getText();
System.out.println("Value: " + text);
String text=driver.findElement(By.xpath("//span[#id='spnLogCount']")).getText();
System.out.println(text);
I updated you code, please use below it will work.
String Text= driver.findElement(By.cssselector("#spnLogCount")).gettext();
System.out.println("total" + Text);
As a JUnit test (and using WebDriverManager to handle the gecko driver):
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import io.github.bonigarcia.wdm.FirefoxDriverManager;
public class FirefoxTest {
private WebDriver driver;
#BeforeClass
public static void setupClass() {
FirefoxDriverManager.getInstance().setup();
}
#Before
public void setup() {
driver = new FirefoxDriver();
}
#After
public void teardown() {
if (driver != null) {
driver.quit();
}
}
#Test
public void test() {
driver.get("http://localhost:8080"); // Here your URL
WebElement webElement = driver.findElement(By.id("spnLogCount"));
System.out.println(webElement.getText());
}
}
I'm trying to follow the Selenium Webdrive Basic Tutorial in the case of using HTML tables here
http://www.toolsqa.com/selenium-webdriver/handling-tables-selenium-webdriver/
The code of "Practice Exercise 1" in that page doesn't work: the problem seems to be about the xpath filter here
String sCellValue = driver.findElement(By.xpath(".//*[#id='post-1715']/div/div/div/table/tbody/tr[1]/td[2]")).getText();
and here
driver.findElement(By.xpath(".//*[#id='post-1715']/div/div/div/table/tbody/tr[1]/td[6]/a")).click();
The page used in the sample code is this one
http://www.toolsqa.com/automation-practice-table/
I've tried to change the code extracting the xpath directly form the page using Firebug and my new code is the following
package practiceTestCases;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PracticeTables_00 {
private static WebDriver driver = null;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.toolsqa.com/automation-practice-table");
//Here we are storing the value from the cell in to the string variable
String sCellValue = driver.findElement(By.xpath("/html/body/div[1]/div[3]/div[2]/div/div/table/tbody/tr[1]/td[2]")).getText();
System.out.println(sCellValue);
// Here we are clicking on the link of first row and the last column
driver.findElement(By.xpath("/html/body/div[1]/div[3]/div[2]/div/div/table/tbody/tr[1]/td[6]/a")).click();
System.out.println("Link has been clicked otherwise an exception would have thrown");
driver.close();
}
}
Trying to execute the error is still
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div[3]/div[2]/div/div/table/tbody/tr[1]/td[2]"}
I'm using Eclipse Luna on Windows 7
Any suggestions? Thank you in advance ...
Cesare
Your xpath is wrong. As I see you try to get the content from the second row/first column (if you doesn't count the headers). Try the following code on http://www.toolsqa.com/automation-practice-table/ page:
/html/body/div[2]/div[3]/div[2]/div/div/table/tbody/tr[2]/td[1]
or
//*[#id='content']/table/tbody/tr[2]/td[1]
If you run getText() it will return the following value: Saudi Arabia
As they given in Practice Test scenario, that xpath has been changed. And ID or className in the xpath might be changed. so change the xpath as per updated HTML code.
Here i have changed everything:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PracticeTables_00 {
private static WebDriver driver = null;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.toolsqa.com/automation-practice-table");
// Here we are storing the value from the cell in to the string variable
String sCellValue = driver
.findElement(
By.xpath(".//*[#id='content']/table/tbody/tr[1]/td[2]"))
.getText();
System.out.println(sCellValue);
// Here we are clicking on the link of first row and the last column
driver.findElement(
By.xpath(".//*[#id='content']/table/tbody/tr[1]/td[6]/a"))
.click();
System.out
.println("Link has been clicked otherwise an exception would have thrown");
driver.close();
}
}
I am trying to copy the table data of the html page which is loaded on the same page after clicking on the 'Get Table' button on the previous page. However, as the page url is not changing I am getting exception of 'No such element' when trying to locate new elements on newly loaded page. Following is the code I tried:
package com.test.selenium;
import java.util.List;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
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;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.Test;
import junit.framework.TestSuite;
public class Example1{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Java Stuff\\Selenium Tutorial\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.oanda.com/currency/table");
WebElement date = driver.findElement(By.name("date"));
date.sendKeys("12/04/10");
WebElement date_frmt = driver.findElement(By.name("date_fmt"));
date_frmt.sendKeys("yy/mm/dd");
WebElement curr = driver.findElement(By.name("exch"));
curr.sendKeys("US Dollar.USD");
Select sel = new Select(driver.findElement(By.name("Currency")));
sel.deselectAll();
List lsize = sel.getOptions();
int count = lsize.size();
for(int j=0;j<count;j++)
{
String lvalue = sel.getOptions().get(j).getText();
sel.selectByVisibleText(lvalue);
}
WebElement crr = driver.findElement(By.name("dest"));
crr.click();
driver.getCurrentUrl();
String table = driver.findElement(By.id("converter_table")).getText();
System.out.println(table);
}
}
According to exception it seems that element not exists on the page, or smth wrong with you xpath. Why you use xpath?! Try css selectors (they are more powerful and stable) =) e.g.
driver.findElement(By.css("#converter_table"));
P.S. if you want to verify that your selector is correct (no matter xpath or css) use dev console in browser (e.g. for css enter $("#converter_table") in console, and if element exists (and this id has no type in the name) then you'll see what this selector will return)). For xpath use $x("xpath")
UPDATE:
Simple solution i think is to add some method which will wait for element, some period of time. Below sample code in C# (test with wait method)
private IWebDriver driver;
[SetUp]
public void SetUp()
{
// Here i just create browser as you (firefox, chrome etc);
driver = CreateBrowser("http://www.oanda.com/currency/table");
}
[TearDown]
public void TearDown()
{
driver.Dispose();
}
[Test]
public void PortTest()
{
var dateElement = driver.FindElement(By.Name("date"));
dateElement.SendKeys("12/04/10");
var dateFrmt = driver.FindElement(By.Name("date_fmt"));
dateFrmt.SendKeys("yy/mm/dd");
var curr = driver.FindElement(By.Name("exch"));
curr.SendKeys("US Dollar.USD");
var crr = driver.FindElement(By.Name("dest"));
crr.Click();
WaitUntilLoad();
var table = driver.FindElement(By.Id("converter_table"));
Console.Write("the text is " + table.Text);
}
public void WaitUntilLoad()
{
int repetitionCount = 0;
bool isLoaded = false;
while (!isLoaded)
{
var table = driver.FindElements(By.Id("converter_table")).Count;
if (table > 0 )
isLoaded = true;
Thread.Sleep(250);
repetitionCount++;
Console.WriteLine("Searching again for element");
if (repetitionCount > 25) break;
}
}
you get NoSuchElement because your xpath seems wrong
try
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//*[#id='content_section']/table")));
String table = driver.findElement(By.xpath(".//*[#id='content_section']/table")).getText();