In my project, I have several datas with checkboxes if I click those different set of data and try to delete that I am getting two types of alerts: one is "deleted successfully" for one data and for other data it showing "data cannot be deleted" popup. How to handle these both in Selenium?
I used if-else statement compared both webelement string using getText() method but it is showing NoSuchElementException.
Here is my code:
WebElement Popup = driver.findElement(By.Xpath="//input[#class='btn-btn-popup']")
WebElement e = driver.findElement(By.xpath="//div[#text='Deleted successfully']");
String Deletepopup = e.getText();
WebElement f = driver.findElement(By.xpath="//div[#text='Data Cannot be deleted']");
String CannotDeltedPopup = f.getText();
if (Deletepopup.equals("Deleted Successfully")) {
Popup.click();
}
else if (CannotDeletedPopup.equals("Data Cannot be deleted")) {
Popup.click();
}
Of course you get NoSuchElementException. You try to find both WebElements, but you can have present only one at a time.
If your action succeed you will have present this
driver.findElement(By.xpath("//div[#text='Deleted successfully']")) and this driver.findElement(By.xpath("//div[#text='Data Cannot be deleted']")) will throw NoSuchElementException and vice versa for action failed.
In your case I recommend you to use try-catch block.
String txt;
try{
txt = driver.findElement(By.xpath("//div[#text='Deleted successfully']")).getText();
}catch(NoSuchElementException e){
try{
txt = driver.findElement(By.xpath("//div[#text='Data Cannot be deleted']")).getText();
}catch(NoSuchElementException e1){
txt = "None of messages was found"; //this will happend when none of elements are present.
}
}
I this case you will try to find message 'Deleted successfully' and if it is not present will try to find message 'Data Cannot be deleted'.
Also I will recommend you to use Explicit Wait, to give your app some time to look for you element before to throw NoSuchElementException.
String txt;
try{
WebDriverWait wait=new WebDriverWait(driver, 10);
txt = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[#text='Deleted successfully']"))
).getText();
}catch(NoSuchElementException e){
try{
WebDriverWait wait=new WebDriverWait(driver, 10);
txt = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[#text='Data Cannot be deleted']"))
).getText();
}catch(NoSuchElementException e1){
txt = "None of messages was found"; //this will happend when none of elements are present.
}
}
This will give 10 seconds time to look for element before to throw NoSuchElementException. You can change this time to how much do you need to increase success of your app.
Related
I'm able to navigate this page [here][1] and enter this website [here][2](TOKEN CREATED FOR EACH DEMO FOR THIS LINK)
I'm also able to extract the value from the round count using this xpath here #class,'coefficient'
I can locate the input element on the left hand side but only one text value is deleted. I want to delete all values and enter 50.
It also seems like I can locate the left hand side button because I'm not getting any exceptions or errors but the button is not clickable.
The below two lines:
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
is basically to clear the input field, since .clear() is not working as expected in this case, we'd have to do CTRL+a and then delete
A full code will look like this:
driver.manage().window().maximize();
driver.get("https://www.spribe.co/games/aviator");
WebDriverWait wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),' Got it')]"))).click();
}
catch(Exception e){
e.printStackTrace();
}
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Play Demo ')]"))).click();
String originalWinHandle = driver.getWindowHandle();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Yes')]"))).click();
List<String> allHandles = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(allHandles.get(1));
WebElement firstInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[text()='BET']/ancestor::div[contains(#class,'feature')]/descendant::input")));
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
firstInput.sendKeys("20");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[text()='BET']/.."))).click();
I'm having error on my code wherein im finding a text but it does not display based on the string I have on my excel. I assume that it is due to frame set up.
here is my code:
'if (driver.findElement(By.linkText(reports)).isDisplayed())
{
System.out.println("report = "+ reports + "does not exist");
}
else
{
System.out.println("report = "+ reports + "does not exist");
}
}
Take note that report = "Order Qty" (text is extracted on excel)
here is the element that I need to find on browser
Instead of finding the element by linkText try finding the elements by text using XPath.
Since you are using the isDisplayed() method to check if the element is visible or not, I'm assuming you are expecting the element to be sometime not visible. In this case, if the element is not visible it will always throw the NoSuchElement exception.
To avoid this, either you have to use the condition inside a try block and handle the exception in the catch block. Or you can use findElements and check the list size which will never throw the exception.
As mentioned by cruisepandey, you should also use explicit waits for element loading delays.
String reports = "Order Qty";
List<WebElement> list = new WebDriverWait(driver,30).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[#class='kpi-report-wrapper']/h2[contains('"+reports+"')]")));
if(list.isEmpty()){
System.out.println("report = "+reports+ "does not exist" );
}else {
System.out.println("report = "+reports+ "exists");
}
You can use this Xpath :
//h2[text()='Order Qty']
Just make sure this shouldn't be in any frame.
However, introducing WebDriverWait will be great idea for stability.
for WebDriverWait :
(new WebDriverWait(driver, 10))
.until(ExpectedConditions.elementToBeClickable (By.xpath("//h2[text()='Order Qty']")));
This would return you a web element.
I'm automating a webstore in selenium/Java. If the user hasn't selected the size of a product, a message comes up stating 'this is a required field' next to the size. I'm trying to write an 'if' statement that asserts whether this message is present and the action to take if it is, but I cannot get it to work. It would be something along the lines of this:
WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector("#advice-required-entry-select_30765)"));
WebElement sizeSmallButton = driver.findElement(By.cssSelector("#product_info_add > div.add-to-cart > div > button"))
if (sizeIsRequiredMsg.equals("This is a required field.")) {
action.moveToElement(sizeSmallButton);
action.click();
action.perform();
}
I've tried a few different variations using the 'this is a required field' message as a web element. Not sure if I need to convert the WebElement for the message to a string somehow? Or include a boolean? Can anyone help?
Try using getText() something like this:
EDIT I have added the correct cssSelectors and added try catch :
WebElement addToCartButton = driver.findElement(By.cssSelector("#product_info_add button"));
action.moveToElement(addToCartButton);
action.click();
action.perform();
try {
WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector(".validation-advice"));
WebElement sizeSmallButton = driver.findElement(By.cssSelector(".swatches-container .swatch-span:nth-child(2)"))
if (sizeIsRequiredMsg.getText() == "This is a required field.") {
action.moveToElement(sizeSmallButton);
action.click();
action.perform();
}
} catch (Exception e) {
System.out.println(e);
logger.log(Level.SEVERE, "Exception Occured:", e);
};
Hope this helps you!
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();
WebElement element1 = driver.get("http://staging.zingoy.com/");
WebElement element11 = driver.get("http://staging.zingoy.com/login");
if (element1!= null && element11!= null ){
driver.findElement(By.xpath("/html/body/div[1]/nav/div/div/div[4]/div/span[2]/a[1]")).click();
System.out.println("LOGin Enter text");
try{
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = (WebElement) wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div[1]/div/div/div[2]/div/div[3]/div/form/div[2]/input")));
element.click();
System.out.println("Clicked on the element successfully");
}catch(Throwable e){
System.err.println("Error came while waiting for the element and clicking on it. "+e.getMessage());
}
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div/div/div[2]/div/div[3]/div/form/div[2]/input")).sendKeys("mdimertest#gmail.com");
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div/div/div[2]/div/div[3]/div/form/div[3]/input")).sendKeys("12345600");
driver.findElement(By.id("login_submit")).click();
driver.get() returns void, you can't assign it to WebElement (first two lines).
driver.get("URL") opens the webpage in the specified URL,which is a null.
It cannot be assigned to a WebElement.
Try assigning any element in the page opened in the browser to element1 and check it for null.