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)
Related
I would like to test how jQuery UI slider
works with Selenide. I tried
$("#L3, #numeric-ui-slider-handle").sendKeys(Keys.ARROW_RIGHT);
but this failed with
Invalid element state: element not interactable
If activate element by hand and press right arrow key it works.
Either I need to send keys globally, not targeted to element, or I need to set it's value somehow directly.
Here is everything you need to move slider, and test it using % like I did below :-
#Test
public void testJQuerySlider() throws InterruptedException {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://jqueryui.com/slider/");
WebDriverWait wait = new WebDriverWait(driver, 30);
Actions action = new Actions(driver);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.className("demo-frame")));
System.out.println("Inside iframe");
WebElement slider = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#slider span")));
slider.click();
String sliderPosition = slider.getAttribute("style");
System.out.println(sliderPosition);
Thread.sleep(2000);
for (int i = 0; i<=10; i++) {
action.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(1000);
}
WebElement newslider = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#slider span")));
String newSliderPosition = newslider.getAttribute("style");
System.out.println(newSliderPosition);
}
I have this react application being tested using selenium webdriver.
if my login is wrong, how do i detect the text using selenium webdriver? I am unable to find the code/ figure out how to trap the pop up message . 'authentication failed'
#Test
public void failed_login() {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\rahul\\Downloads\\chromedriver_win32_83\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://testingapp.workspez.com");
driver.manage().window().maximize();
WebElement username = driver.findElement(By.id("field_email"));
WebElement password = driver.findElement(By.id("field_password"));
WebElement login = driver.findElement(By.xpath("//*[text()='Log In']"));
username.sendKeys("wrongemail#gmail.com");
password.sendKeys("wrongpassword");
login.click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
String url = driver.getCurrentUrl();
assertEquals(url, "http://testingapp.workspez.com/login");
}
You can use below code to verify if authentication failed pop up is displayed or not:
List<WebElement> popUpElement = driver.findElements(By.id("client-snackbar");
if(popUpElement.size() != 0){
System.out.println("Pop up is Present "+popUpElement.get(0).getText());
}else{
System.out.println("Pop up is Absent");
}
After you perform click, you can use Explicit Wait:
try{
WebDriverWait wait = new WebDriverWait(driver, 10); //10 seconds
WebElement messageElement = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//*[#id = 'client-snackbar']")
)
);
//if reach here, means the error is visible.
System.out.println(messageElement.getText());
}catch(TimeoutException ignored){
//if trigger timeoutexception
//that means the element with message is not visible, that means no error
}
This will wait 10 seconds for the element to be visible.
If it is not visible, it will throws TimeoutException which you can simply ignore.
That means the error was not visible in first 10 seconds after click.
You can change the time with whatever you want.
You can find the locator for that toast message.
For locating web element
Go to your login.
Enter your invalid credentials.
Press F12 and go to console/Sources
Click on login to get your message.
Press F8 to pause it. Now you can inspect your element.
So from webelement you can fetch text with gettext() method.
You can apply explicit wait to wait for your error message.
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 have list of Hyperlinks in one page, when i click the links , they are redirecting to the new tab. how do i find out whether the page is loaded or not. i have used the do while loop for find out the element is enabled or not. but i am getting "no such element" only. could you please help on this.. Below is the piece of code. i have tried with Explicit wait also . but getting the same issue.
WebElement element7 = driver.findElement(By.id("MenuControlBNY_MenuNavBar_MenuControlBNY_MenuNavBar_p11__Tree_item_2_cell"));
if (element7.isEnabled())
{
element7.click();
System.out.println(" Report is selected");
}
boolean element8 = false;
int count = 0 ;
do
{
element8 = driver.findElement(By.id("working")).isEnabled();
System.out.println("Report is loaded");
count = count+1;
if(count == 1000)
{
break;
}
}while(element8 == true);
I use the following, its fairly self explanatory.
private static WebDriverWait wait = new WebDriverWait(driver, 60);
private static JavascriptExecutor js = (JavascriptExecutor) driver;
public static void waitForPageLoaded() {
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
Boolean res = (js.executeScript("return document.readyState").equals("complete"));
System.out.println("[DEBUG] waitForPageLoaded: " + res);
return res;
}
});
}
EDIT: This will return true when the page is in a ready state ie the page is loaded. So you would call the above method prior to searching for your element.
You can set an implicit wait which will wait for the elements when finding them for a 15 seconds
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
or explicitly:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("working")));
From the information you have provided, I am assuming you have clicked the link and the page is opened in a new tab and then you are getting nu such elment exception.
In this case you need to switch to the new tab using window handles and use explict wait for element.here is sample code
String parentWindow= driver().getWindowHandle();
element7.click();
Set<String> myset = driver().getWindowHandles();
myset.remove(parentWindow);
driver().switchTo().window((String)myset.toArray()[0]);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(locator)));
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