I am using Selenium v2.30.0 and Firefox 19.0. When I execute the below code:
public class First_Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}
I get an error saying:
"Unable to connect to host localhost on port 7055 after 45000 ms"
I've searched everywhere for an answer with no success. All help appreciated.
Seems like some problem while waiting for the response
try this code instead:
public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("Cheers!");
// Sleep until the div we want is visible or 5 seconds is over
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
WebElement resultsDiv = driver.findElement(By.className("gssb_e"));
// If results have been returned, the results are displayed in a drop down.
if (resultsDiv.isDisplayed()) {
break;
}
}
// And now list the suggestions
List<WebElement> allSuggestions = driver.findElements(By.xpath("//td[#class='gssb_a gbqfsf']"));
for (WebElement suggestion : allSuggestions) {
System.out.println(suggestion.getText());
}
}
You need to update Selenium to v2.31. Firefox 19 is not supported in anything lower.
https://code.google.com/p/selenium/downloads/list
Related
I tried the following code in Selenium to get the row values.
public static void main(String[] args) throws InterruptedException {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www2.asx.com.au/");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
WebElement cookies = driver.findElementByXPath("//button[text()='Accept All Cookies']");
wait.until(ExpectedConditions.elementToBeClickable(cookies)).click();
} catch (Exception e) {
System.out.println("cookies pop up not found");
}
WebElement el = driver
.findElementByXPath("//*[#class='markit-home-top-five aem-GridColumn aem-GridColumn--default--12']");
wait.until(ExpectedConditions.visibilityOf(el));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", el);
List<WebElement> elements = driver.findElementsByXPath("//caption[text()='Gains']//ancestor::table//tr");
for (int i = 1; i <= elements.size(); i++) {
Thread.sleep(2000);
System.out.println(driver.findElementByXPath(
"//caption[text()='Gains']//ancestor::table//tr[" + i + "]//span[#class='value-with-arrow']")
.getText());
}
}
I faced two issues:
The 'Allow all cookies' button is not getting clicked and the pop up remains there. 'cookies pop up not found' is getting printed in the output.
The value of the tables are not getting printed without sleep. in the below output ,it is shown that the first text value is printed as -- as the value was still loading. How to provide till the value is fully loaded.
Thanks in advance!
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("element_id"), "The Text"));
use webdriver wait , you can use expected condition texttobepresent or element to be present
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#textToBePresentInElementLocated(org.openqa.selenium.By,java.lang.String)
I am trying to open one by one link in new Tab in selenium Java, but only one link is opening the first time but For Loop goes wrong when open a second link, can anyone please help me to figure this out.
Here is my Code.
public class Link_Open_In_New_Tab {
public WebDriver driver;
#BeforeTest
public void OpenBrowser() {
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nopcommerce.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void OpenLink() throws InterruptedException {
List<WebElement> ProMenu;
WebElement SubLinks;
driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a")).click();
ProMenu = driver.findElements(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li/a"));
for (int i = 0; i < ProMenu.size(); i++) {
SubLinks = driver
.findElement(By.xpath("//ul[#class='top-menu']/li[" + (i + 1) + "]/ul[#class='sublist']/li/a"));
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).click(SubLinks).keyUp(Keys.CONTROL).build().perform();
Thread.sleep(2000);
String winHandleBefore = driver.getWindowHandle();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
Thread.sleep(2000);
driver.close();
Thread.sleep(2000);
driver.switchTo().window(winHandleBefore);
Thread.sleep(2000);
//driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a")).click();
//Thread.sleep(2000);
}
}
}
You were trying to open all the sublinks from the product menu. But your sublink xpath is pointing to the first sublink of all the menu (li[" + (i + 1) + "]/ul[#class='sublist']/li/a). So, you need to modify your sublink xpath as below and then try
SubLinks = driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li[" + (i + 1) + "]/a"));
You have to hover on Product, to get all the sub menus items. After then you can simulate keyboard strokes using Actions class which is available in Selenium and JAVA.
You can try this code :
public class Ashish {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user***\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nopcommerce.com/");
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a"))).build().perform();
List<WebElement> element = driver.findElements(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li/a"));
for(WebElement ele:element) {
action.keyDown(Keys.LEFT_CONTROL).moveToElement(ele).click().keyUp(Keys.LEFT_CONTROL).build().perform();
}
}
}
UPDATE 1 :
public class Ashish {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user***\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nopcommerce.com/");
WebDriverWait wait = new WebDriverWait(driver, 10);
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a"))).build().perform();
List<WebElement> element = driver.findElements(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li/a"));
System.out.println(element.size());
for(int i = 0 ; i<element.size() ; i++) {
action.keyDown(Keys.LEFT_CONTROL).moveToElement(wait.until(ExpectedConditions.elementToBeClickable(element.get(i)))).click().keyUp(Keys.LEFT_CONTROL).build().perform();
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
System.out.println(driver.getTitle());
driver.close();
driver.switchTo().window(tabs.get(0));
}
}
}
Console output :
9
nopCommerce - ASP.NET free shopping cart solution. What is nopCommerce?
nopCommerce - ASP.NET Open-source Ecommerce Shopping Cart Solution
nopCommerce - ASP.NET open source eCommerce solution. Feature list.
nopCommerce - Shopping Cart Demo & Shopping Cart Solution
nopCommerce - open source shopping cart. Showcase. Live Shops.
nopCommerce - open source shopping cart. Case Studies and Success Stories.
nopCommerce - ASP.NET open source shopping cart. Roadmap.
nopCommerce copyright removal key - nopCommerce
The nopCommerce Public License Version 3.0 ("NPL") - nopCommerce
If your intention is to test the links title to be working as expected or not then why need to you Crtl+click.
As per development, link here is to click but not ctrl+click, personally i am not willing to do this action.
Create variable say int i=1;
in loop like used, go for normal click and verify title. then increment i and go for browser back.
I am trying to navigate to "https://developers.google.com/".
I then click a link by the xpath and redirect to another page.
Everything works as far as finding elements and clicking links on the first page.
But I cannot seem to find the elements I want to look for after I go to the new page.
The redirected page is "https://cloud.withgoogle.com/next18/sf/?utm_source=devsite&utm_medium=hpp&utm_campaign=cloudnext_april18"
This is checking if text is equal.
confirmText("Imagine", "//*[#id=\"main\"]/span/div[2]/div/div/div[1]/div[1]/div/div[1]/div[2]/h3");
public static void confirmText(String text, String xpath) {
System.out.println("Trying to confirm that given string is equal to the text on page.");
WebElement element = driver.findElement(By.xpath(xpath));
System.out.println("Test case: " + text);
System.out.println("Result: " + element.getText());
if (element.getText() == text) {
System.out.println("\nEquals.");
}
else {
System.out.println("\nDoes not equals.");
}
System.out.println("\n\n");
}
This is sending keys.
public static void sendKeys() {
WebElement firstname = driver.findElement(By.id("firstName"));
firstname.sendKeys("John");
WebElement lastname = driver.findElement(By.xpath("//*[#id=\"lastName\"]"));
lastname.sendKeys("Doe");
WebElement email = driver.findElement(By.xpath("//*[#id=\"email\"]"));
email.sendKeys("johndoe#gmail.com");
WebElement jobtitle = driver.findElement(By.xpath("//*[#id=\"jobTitle\"]"));
jobtitle.sendKeys("Software Engineer");
WebElement company = driver.findElement(By.xpath("//*[#id=\"company\"]"));
company.sendKeys("ABCD");
}
The error is
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="main"]/span/div[2]/div/div/div[1]/div[1]/div/div[1]/div[2]/h3"}
Only the first page actually waits to finish loading before the script starts. If you navigate away form the page then you will need to manually wait. Without waiting, the script will continue to the next command immediately after clicking the link that changes the page, and since the page is not loaded yet you will not find the element. This gives the error.
The simplest way to wait is by using "WebDriverWait"
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(>someid>)));
There are more simple examples here:
http://toolsqa.com/selenium-webdriver/wait-commands/
You can try this xpath using for imagine and put some wait as #chris mentioned
//div//h3[contains(text(),'Imagine')]
JavascriptExecutor can be used to get the value of an element,
Refer code,
confirmText("Imagine", "//*[#id=\"main\"]/span/div[2]/div/div/div[1]/div[1]/div/div[1]/div[2]/h3");
public static void confirmText(String text, String xpath) {
System.out.println("Trying to confirm that given string is equal to the text on page.");
WebElement element = driver.findElement(By.xpath(xpath));
JavascriptExecutor executor = (JavascriptExecutor)driver;
System.out.println("Test case: " + text);
System.out.println("Result: " + executor.executeScript("return arguments[0].innerHTML;", element););
if (text.equals(executor.executeScript("return arguments[0].innerHTML;", element))) {
System.out.println("\nEquals.");
}
else {
System.out.println("\nDoes not equals.");
}
System.out.println("\n\n");}
I'm trying to trawl this website: http://www.jackson-stops.co.uk/
The data is not showing in the URL so I'm using a chromedriver.
My code is:
public static void main(String[] args) {
//setup chromedriver
File file = new File("C:\\Users\\USER\\Desktop\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
try {
driver.get("http://www.jackson-stops.co.uk/");
//begin the simulation
WebElement menu = driver.findElement(By.xpath("//*[#id=\"sliderLocation\"]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", menu);
menu.sendKeys("Knightsbridge");
Thread.sleep(4000);
Select menu2 = new Select(menu);
menu2.selectByVisibleText("Knightsbridge");
Thread.sleep(4000);
} catch (Exception exp) {
System.out.println("exception:" + exp);
//close and quit windows
driver.close();
driver.quit();
}
//close and quit windows
driver.close();
driver.quit();
}
The error that I get is:
exception:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"
How would I be able to select a location and hit enter because I tried inspecting the HTML and the options are dynamically loaded so not visible!
You are trying to select an element but it's not select list, it's a link, So all you have to do is to click that element, that's all
First of all pass value
driver.findElement(By.xpath("//*[#id='sliderLocation']")).sendKeys("Knightsbridge")
Once it's done, it populate the values, So You need to click one of option, So you can directly click the element like this(since this population is taking time, you need to use implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS))
And then write
driver.findElement(By.xpath("//a[text()='Knightsbridge, London']")).click()
Or if you want to choose the element which consist of Knightsbridge then write the following code and this will choose the first option which consist of Knightsbridge then write
driver.findElement(By.xpath("//a[contains(text(),'Knightsbridge']")).click()
You don't have to use sleep statement anywhere in your selenium code, selenium automatically waits after the click until everything settle down properly. The one exceptional case is, If your page got refreshed after placing the value in your text box(Not necessary for select_list), then you need to use the implicit wait, otherwise even implicit wait is not necessary.
The above code I converted from Ruby to Java, the original code which I used to check is from selenium Ruby binding, the code is below
#driver.find_element(:xpath, "//*[#id='sliderLocation']").send_keys "Knightsbridge"
#driver.manage.timeouts.implicit_wait = 10
#driver.find_element(:xpath, "//a[contains(text(),'Knightsbridge')]").click
#driver.find_element(:xpath, "//a[text()='Knightsbridge, London']").click
You can do as below:
String requiredCity = "London";
List<WebElement> menu2 = driver.findElements(By.xpath("//ul[#id='ui-id-3']/li"));
System.out.println("Total options: "+menu2.size());
for(int i=0;i<menu2.size();i++)
{
String CurrentOption = menu2.get(i).getText();
if(CurrentOption.contains(requiredCity)){
System.out.println("Found the city : "+CurrentOption);
menu2.get(i).click();
}
}
This is the full solution using Ranjeet's answer.
File file = new File("C:\\Users\\USER\\Desktop\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
try {
driver.get("http://www.jackson-stops.co.uk/");
//begin the simulation
WebElement menu = driver.findElement(By.xpath("//*[#id=\"sliderLocation\"]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", menu);
menu.sendKeys("London");
Thread.sleep(4000);
String requiredCity = "London";
List<WebElement> menu2 = driver.findElements(By.xpath("//ul[#id='ui-id-3']/li"));
System.out.println("Total options: " + menu2.size());
for (int i = 0; i < menu2.size(); i++) {
String CurrentOption = menu2.get(i).getText();
if (CurrentOption.contains(requiredCity)) {
System.out.println("Found the city : " + CurrentOption);
menu2.get(i).click();
Thread.sleep(6000);
menu.sendKeys(Keys.RETURN);
}
}
Thread.sleep(8000);
} catch (Exception exp) {
System.out.println("exception:" + exp);
//close and quit windows
driver.close();
driver.quit();
}
//close and quit
driver.close();
driver.quit();
WebElement selectMyElement = driver.findElement((By.xpath("//div/select/option[#value='Your value']")));
selectMyElement.sendKeys("Your value");
Actions keyDown = new Actions(myLauncher.getDriver());
keyDown.sendKeys(Keys.chord(Keys.DOWN, Keys.DOWN)).perform();
I am trying to build a simple function in selenium that given a text brings back all the result from Google. I'm using xpath to find all result elements. Although "//a[#class='l']" works as a legit xpath with firebug the resulting list is empty when I run the code.
public void testSearch() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("obama twitter");
query.submit();
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
WebElement resultsDiv = driver.findElement(By.className("gssb_e"));
if (resultsDiv.isDisplayed()) {
break;
}
}
List<WebElement> weblinks = driver.findElements(By.xpath("//a[#class='l']"));
for (WebElement suggestion : weblinks) {
System.out.println(suggestion.getText()+"\n");
System.out.println("==> "+suggestion.getAttribute("href")+"\n");
}
}