I am trying to close a pop up window which is not allowing my code to execute further. But I am unable to do that. There is a a pop up window which says 'Free pound 5 voucher' which is not getting closed.
Below is my code. Please check and suggest.
public class Alldetails {
WebDriver driver;
public List<String> links1 = new ArrayList<String>();
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "C:\\Pankaj\\chromedriver.exe");
driver = new ChromeDriver();
// driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#Test
public void f() {
driver.get("http://www.debenhams.com/kids/t-shirts-tops/boys");
driver.findElement(
By.xpath(".//*[#id='dijit__WidgetsInTemplateMixin_0']/div/div[1]/button"))
.click();
WebElement a = driver.findElement(By.className("products_count"));
String product_count = a.getText();
Integer x = Integer.valueOf(product_count);
System.out.println(x);
for (int i = 1; i < (x / 60) + 1; i++) {
driver.get("http://www.debenhams.com/kids/t-shirts-tops/boys" + "?pn=" + i);
List<WebElement> links = driver
.findElements(By.className("item_container").tagName("a"));
for (WebElement abcx : links) {
String ax = abcx.getAttribute("href");
// if(!links1.contains(ax))
links1.add(ax);
}
for (String b : links1) {
if (b.contains("/webapp/wcs/stores/servlet/prod"))
System.out.println(b);
}
}
}
#AfterTest
public void afterTest() {
}
}
You need to do something like this:
Alert alert = driver.switchTo().alert();
// Prints text and closes alert
System.out.println(alert.getText());
alert.accept();
or
alert.dismiss();
according to your needs.
EDIT
You may get an AlertNotPresentException if your code runs before the alert appears. In order to avoid that you may add a delay like this:
WebDriverWait wait = new WebDriverWait(driver, 15, 100)
wait.until(ExpectedConditions.alertIsPresent())
This will make Selenium wait 15 seconds checking every 100 milliseconds if the alert appeared. This snippet is not mine and had been taken from here: Selenium how to get the alert Alert message
Related
Proble statement is as follows:
Open www.google.com in browser.
Add selenium hq in search
findout search result for wikipedia link for selenium hq.
print description which is displayed next to link to console.
search result is sometimes appears on 1st page and sometimes not.
i am able to search on 1st page and if its not there then traverse to 2nd page and so on.
but not able to get that description.
My code is:
WebDriver driver = null;
String baseUrl = "https://www.google.com";
System.setProperty("webdriver.gecko.driver", "C:\\SeleniumDrivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//input[#class='gLFyf gsfi']")).sendKeys("Selenium HQ");
driver.findElement(By.xpath(".//input[#class='gLFyf gsfi']")).sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
List<WebElement> linkElements = new ArrayList<WebElement>();
ListIterator<WebElement> itr = null;
WebElement toClick = null;
int pageNumber = 1;
WebDriverWait wait = new WebDriverWait(driver, 10);
boolean flag = false;
while (!flag)
{
linkElements = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='s']")));
itr = linkElements.listIterator(); // re-initializing iterator
while (itr.hasNext())
{
toClick = itr.next();
if (toClick.getText().contains("Wikidata"))
{
String desc = toClick.getText();
System.out.println(desc);
flag = true;
break;
}
}
if (!flag)
{
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]")).click();
pageNumber++;
linkElements.clear(); // clean list
// wait.until(ExpectedConditions.textToBePresentInElementLocated(
//By.xpath("//div[#class='st']"), pageNumber + ""));
}
}
driver.close();
looking for a solution to this problem..
Hi i have written this code . Now for date part it works as expected but for time part neither it is giving any exception nor it is printing time slots .
URL:-https://www.dineout.co.in/delhi/boa-village-civil-lines-north-delhi-21335
WebDriver driver;
String datee="";
String t="";
public RDP(WebDriver ldriver){
this.driver=ldriver;
}
#FindBy(how=How.XPATH,using="//input[#class='form-control']")
WebElement Time_selector;
#FindBy(how=How.XPATH,using="//*[#class='do do-calender-icon']")
WebElement calender;
public void logged_in_user_booking() throws InterruptedException
{
calender.click();
Thread.sleep(4000);
List<WebElement> dates= driver.findElements(By.cssSelector("ul.days li"));
//System.out.println(dates);
for(int i=0 ;i<dates.size();i++)
{
datee = dates.get(i).getText();
if(datee.equalsIgnoreCase("31"))
{
dates.get(i).click();
break;
}
}
List<WebElement> time_slots = driver.findElements(By.cssSelector("div.timings-wrap ul li"));
for(int j=0 ;j<time_slots.size();j++)
{
t = time_slots.get(j).getText();
System.out.println(t);
/* if(t.equalsIgnoreCase("03:00 pm"))
{
time_slots.get(j).click();
break;
}
*/
}
The time slots take some time to load, so if you didn't set implicitlyWait driver.findElements won't wait for any element to exist and will return an empty list. Adding implicitlyWait, one time right after the driver instantiation, should solve this problem (you should add it anyway).
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
You can also use explicit wait with Expected Conditions
WebDriverWait wait = new WebDriverWait(driver, 10);
List<WebElement> time_slots = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.timings-wrap ul li")));
I am trying to navigate through search results from google with selenium webdriver. I have a interface for user to inset word to search and site title to choose. If the result is not on the first page the driver should go to next page to look for the site, and if not there than to next page and so on..
Somehow I don't manage to get beyond the second page end if I did get to the second page and the right site is there, the driver doesn't click on it.
Here is some of the code in Java:
private void setLoopNum(int l){
String getText = urlText.getText();
String getSiteName = linkToChoose.getText();
System.setProperty("webdriver.chrome.driver", "C:\\selenium-2.44.0\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); //Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for(int i=0;i<l;i++){
//WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
//driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement element1 = driver.findElement(By.name("q"));
element1.sendKeys(getText);
element1.submit();
//driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); //wait for page to load
//try{
boolean flag = false;
String page_number = "1";
while(! flag){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement eachResult: linkElements){
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
eachResult.findElement(By.xpath("//a[#href='" + getSiteName + "']")).click();;
flag =true;
}else{
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
linkElements.clear(); //celean list
break;
} //end else
}
}//end while loop
//}catch(Exception e){
// System.out.println("Error!");
// }
}
driver.quit(); //clear memory
}
Three things that you are missing in your code:
Firstly, in your code you are looking for only first element in your list.
Secondly, in getAttribute you are passing link instead of href:
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
it should be:
if(eachResult.getAttribute("href").equals(getSiteName)){
Thirdly, on clicking next the page is loaded via Google Ajax Api. Thus webdriver click will never block the execution of your code and will load linkElements with previous page links only. To avoid this let the driver get refreshed or put some wait for certain condition in your code.
Can u try out with this code:
WebDriverWait wait = new WebDriverWait(driver, 10)
while (!flag) {
// get all the search results
linkElements = wait
.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
for (WebElement eachResult : linkElements) {
if (eachResult.getAttribute("href").contains(getSiteName)) {
eachResult.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // celean list
wait.until(ExpectedConditions
.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber
+ "")); // Checking whether page number is changed as expected.
}
}// end while loop
EDIT:
List<WebElement> linkElements = new ArrayList<WebElement>();
ListIterator<WebElement> itr = null;
System.setProperty("webdriver.chrome.driver",
"webdrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); // Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://google.com");
WebElement element1 = driver.findElement(By.name("q"));
WebElement toClick = null;
element1.sendKeys(getText);
element1.submit();
// try{
int pageNumber = 1;
WebDriverWait wait = new WebDriverWait(driver, 10);
boolean flag = false;
while (!flag) {
linkElements = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
itr = linkElements.listIterator(); // re-initializing iterator
while (itr.hasNext()) {
toClick = itr.next();
if (toClick.getAttribute("href").contains(getSiteName)) {
toClick.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // clean list
wait.until(ExpectedConditions.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber + ""));
}
}
driver.quit(); // clear memory
}
It looks like you're moving to the next page every time ANY of the WebElements in linkElements isn't what you're looking for. This will cause problems, as you need to relocate any elements that are re-rendered.
Give this a shot:
boolean found = false;
int page_number = 1; //If you need this as a string, you can make it one later
while(! found){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement result: linkElements){
if(result.getAttribute("href").equals(getSiteName))
{
result.click();
found=true;
break;
}
}//End of foreach-loop
if(!found){
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
page_number++;
}
}//End of while-loop
Also, you'll want to have some element-finding protection. Say that you search for something that has 0 results, or only one page of them (rare though that is). In the first case, you're lucky, because driver.findElements() should just return an empty list rather than throwing some exception, and the foreach loop just won't run, but in both cases, there won't be the anchor #pnnext, which will cause driver.findElement to throw an exception when you search for it. There are several ways to protect against this, such as writing a small wrapper function (IIRC, they have a simple implementation for findelementwithtimeoutwait() written on the Selenium website somewhere). I suggest you pick/write one and start using it, instead of the raw Selenium functions.
I am newbie to Selenium and not able to select date website http://www.redbus.in.
Can some one help me out? I tried to pass value to the read only text box, but it was in vain.
public static void setup() throws Exception {
System.out.println("Browser Set up start.. ");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.get("http://www.redbus.in/");
System.out.println("Browser Set up Completed ");
}
#Test
public static void SelectSrcDest() throws Exception {
System.out.println("Constructing Url to open");
driver.findElement(By.id("txtSource")).sendKeys("Bangalore");
driver.findElement(By.id("txtDestination")).sendKeys("Chennai");
driver.findElement(By.xpath("html/body/div[2]/div/section/div[1]/img")).click();
driver.findElement(By.xpath("html/body/div[2]/div/section/div[1]/img")).click();
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("window.document.getElementById('txtOnwardCalendar').setAttribute('value','27-Mar-2014')");
driver.findElement(By.xpath("html/body/div[2]/div/section/div[4]/button")).click();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
setup();
SelectSrcDest();
}
You can use xPath to find the element by text and then use the div id & table class to choose which trip & month to pick.
For instance in order to select the date of journey:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.redbus.in");
driver.findElement(By.id("txtOnwardCalendar")).click();
By locator = By.xpath("//div[#id='rbcal_txtOnwardCalendar']" +
"/table[#class='monthTable first']" +
"//td[contains(text(), '10')]");
driver.findElement(locator).click();
would select the 10th day of the first month. If you use monthTable last as the class instead, you get 10th day of the second month. And if you change the div id into rbcal_txtReturnCalendar, you can pick a date for the return trip.
You can try the following piece of code. It works perfect
driver.findElement(By.id("DDLSource")).sendKeys("C");
driver.findElement(By.xpath("//dl[#id = 'lis']//dt[text()='Chennai']")).click();
driver.findElement(By.id("DDLDestination")).sendKeys("t");
driver.findElement(By.xpath("//dl[#id = 'dis']//dt[text()='Theni']")).click();
driver.findElement(By.className("calenImg")).click();
driver.findElement(By.xpath("//td[text()='Feb']/../..//a[text()='17']")).click();
driver.findElement(By.id("calendar1")).click();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//td[text()='Feb']/../..//a[text()='20']")).click();
Try this to select the date:
driver.findElement(By.id("give id")).click();
WebElement selectElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("ui-datepicker-year")));
Select select = new Select(selectElement);
select.selectByValue("2012");
Thread.sleep(6000);
WebElement dateWidget = driver.findElement(By.id("ui-monthpicker-div"));
List<WebElement> columns011=dateWidget011.findElements(By.tagName("td"));
for (WebElement cell: columns011){
//Select Month
if (cell.getText().equals("Feb")){
cell.findElement(By.linkText("Feb")).click();
break;
}
}
Try to figure out the element through ID.. Its very easy to target exactly by the ID.
driver.findElement(By.id("txtOnwardCalendar")).click();
WebElement selectElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("monthTable first")));
Select select = new Select(selectElement);
select.selectByValue("2012");
Thread.sleep(6000);
WebElement dateWidget = driver.findElement(By.id("monthTitle"));
List<WebElement> columns011=dateWidget011.findElements(By.tagName("td"));
for (WebElement cell: columns011){
//Select Month
if (cell.getText().equals("Feb")){
cell.findElement(By.linkText("Feb")).click();
break;
}
}
I am trying to select the drop down of this site and proceed to buy a show, but I am not able to do so please help.
System.setProperty("webdriver.chrome.driver", "C:/Selenium/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.theatrepeople.com/");
driver.findElement(By.id("edit-show")).click();
new Select(driver.findElement(By.id("edit-show"))).selectByVisibleText("The 39 Steps");
driver.findElement(By.id("edit-date-datepicker-popup-0")).click();
driver.findElement(By.linkText("27")).click();
driver.findElement(By.id("edit-ticket-no")).click();
new Select(driver.findElement(By.id("edit-ticket-no"))).selectByVisibleText("1 ticket");
driver.findElement(By.id("edit-submit-1")).click();
There is no reason to click on the select form (driver.findElement(By.id("edit-show")).click()), you just want to select an element (using the Select class). This is also probably the reason why your code is not working. You should remove this line and it should work.
Use the following code. It uses java script to select a text based upon it's valued. Really nice question. I also got to learn.
static WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D:\\ToCustomer_31_5_13\\src\\main\\resources\\Drivers\\chromedriver.exe");
driver = new FirefoxDriver();
driver.get("http://www.theatrepeople.com/");
driver.findElement(By.id("edit-show")).click();
WebElement show = driver.findElement(By.xpath("//div[#id = 'edit-show-wrapper']//div[#id = 'showNameWrap']"));
List<WebElement> l = show.findElements(By.tagName("option"));
String valueToSelect = getAttibuteValueForShow(l, "The American Plan");
driver.findElement(By.id("mini-basket-ajax")).click();
selectValueInDropDown(valueToSelect);
}
public static String getAttibuteValueForShow(List<WebElement> li, String showName)
{
int j =0;
String value = null;
for(int i =0; i<li.size(); i++)
{
j = j +1;
String dropDownText = li.get(i).getText();
if(dropDownText.equalsIgnoreCase(showName))
{
value = driver.findElement(By.xpath("//div[#id = 'edit-show-wrapper']//div[#id = 'showNameWrap']//option[" + j +"]")).getAttribute("value");
System.out.println(value);
break;
}
}
return value;
}
public static void selectValueInDropDown(String value)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
String jsCmd = "document.getElementsByName('show')[0].value='" + value + "'";
js.executeScript(jsCmd);
}
The following code will work
WebDriver driver = new ChromeDriver();
driver.get("http://www.theatrepeople.com/");
WebElement dropDown = driver.findElement(By.id("edit-ticket-no"));
Select sel = new Select(dropDown);
sel.selectByVisibleText("1 ticket");