Finding and clicking on elements in a new page by Selenium - selenium

The situation is as such -
From "something/login.php" page, i am clicking on a button which takes me to the home page "something/dashboard.php"
Trying to click on a element on the new page "something/dashboard.php" but unable to locate element.
I have then checked the currenturl with
String actualUrl = driver.getCurrentUrl();
and i am getting "something/login.php" page which means the driver is in the previous page. How do i change my focus to the new page and find elements of it?
Here is my code -
public static void main(String[] args) throws InterruptedException {
//Set chromedriver path
System.setProperty("webdriver.chrome.driver", "E:\\Tools\\New folder\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "something";
driver.get(url);
driver.findElement(By.id("username")).sendKeys("something");
driver.findElement(By.id("password-field")).sendKeys("something");
driver.findElement(By.id("btn3")).click();
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);}
driver.findElement(By.xpath("//*[#id=\"accordion\"]/li[3]/a")).click();

Please use below code after login
driver.navigate().refresh();

Related

How to Capture Full page screenshot of using selenium WebDriver

I have created a Selenium Full page screenshot test for Responsive tests using selenium.
But if I am going to run against the SharePoint Site then it's not taking a full-page screenshot but If I'll give any particular public site to capture the screenshots.
Here is the code snippet:
public class resTest {
#Test(groups = {"Test1"})
public void ResTest() throws InterruptedException, IOException {
System.setProperty("webdriver.gecko.driver", "C:\\browserdriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(getUrl());
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
//Enter email ID
WebElement enterEmail = wait.until(ExpectedConditions.elementToBeClickable(By.name("loginfmt")));
enterEmail.sendKeys(getUsername());
WebElement clickNext = wait.until(ExpectedConditions.elementToBeClickable(By.className("win-button")));
clickNext.click();
//Enter Password
WebElement SubmitPass = wait.until(ExpectedConditions.elementToBeClickable(By.name("passwd")));
SubmitPass.sendKeys(getPassword());
//Click on Sign In button
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#value='Sign in']")));
element.click();
WebElement afterNext = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#value='No']")));
afterNext.click();
Thread.sleep(9000);
File src = ((FirefoxDriver)driver).getFullPageScreenshotAs(OutputType.FILE);
FileHandler.copy(src, new File(System.getProperty("user.dir")+"/Res2/screen.png"));
}
}
On a headless browser I use the following to get a screen of the full page
full_width = driver.execute_script('return document.body.parentNode.scrollWidth')
full_height = driver.execute_script('return document.body.parentNode.scrollHeight')
driver.set_window_size(full_width, full_height)
driver.save_screenshot(path)
The advantage of a headless browser window is that you can resize it to whatever size you want, even if it is larger than your screen resolution. For example, if your screen is 1920x1080 and you resize the headless browser window to 1000x5000 and take a screenshot, then the image will be 1000x5000 pixels.

clicking multiple links on a given webpage to open them in a new tab gives error

I'm trying to open each link on the given web page in a new tab But by clicking two links, it throws this error. Any suggestions would help. Thanks.
Here is my code:
public class FirstClass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("https://www.google.com/");
Actions action = new Actions(driver);
List<WebElement> web = driver.findElements(By.tagName("a"));
for (int i = 1; i < web.size(); i++) {
System.out.println(web.get(i).getText());
action.moveToElement(web.get(i)).keyDown(Keys.CONTROL).click().build().perform();
}
}
}
Here is an error which I got -
Exception in thread "main" org.openqa.selenium.JavascriptException: javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite.
The code fails as some of the links in the Google Webpage are not displayed and can only be seen when certain actions are performed. The first link which results in failure of the code is "Report inappropriate predictions" link which can be seen when one clicks on the search bar.
To handle these links, one needs to traverse through the DOM when things get tricky. So, I added a JavaScriptExecutor to the code which comes into picture when a given link is not displayed.
Please use the below-mentioned code to open every link in the Google HomePage:
System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("https://www.google.com/");
Actions action = new Actions(driver);
List<WebElement> web = driver.findElements(By.tagName("a"));
for (int i = 0; i < web.size(); i++) {
if(web.get(i).isDisplayed()){
action.moveToElement(web.get(i)).keyDown(Keys.CONTROL).click().build().perform();
}else{
String url = web.get(i).getAttribute("href");
((JavascriptExecutor)driver).executeScript("window.open('" + url + "', '_blank');");
}
}
Hope this helps.

Using Selenium web driver, not able to take Screenshot of web page with tool-tip text displayed on it

I am trying to take screen shot of the web page showing the tool tip text, but I can only see WebElement text being highlighted after mouse hover, but tool tip is not even shown up on the web page during script execution.
Here is the piece of code, that I am trying to execute. Need help to figure out what am I missing..
public static void main(String[] args) throws InterruptedException, IOException, AWTException
{
String URL = "https://www.rediff.com";
System.setProperty("webdriver.chrome.driver", "C:\\Users\\bhara\\eclipse-workspace\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(URL);
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
String WebElementXpath = "//*[#class='mailicon']";
String toolTipText ;
WebElement ToolTipElement = driver.findElement(By.xpath(WebElementXpath));
Actions act1 = new Actions(driver);
act1.moveToElement(ToolTipElement).build().perform();
Robot robot = new Robot();
Point point;
point = ToolTipElement.getLocation();
int x = point.getX();
int y = point.getY();
robot.mouseMove(x,y);
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("screenshot.png"));
System.out.println( ToolTipElement.getAttribute("title"));
}
I don't see any such issues in your code block as such. However if you observe the HTML DOM of the WebElement:
The text Lightning fast free email is the title attribute but not the tooltip as such. Hence through using Actions class to Mouse Hover over the element won't bring up the popup. However, I made some small changes and executed you code to get the same result as follows:
Code Block:
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.rediff.com/");
new Actions(driver).moveToElement(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#class='mailicon']")))).build().perform();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Rediffmail.png"));
System.out.println(driver.findElement(By.xpath("//a[#class='mailicon']")).getAttribute("title"));
driver.quit();
Console Output:
Lightning fast free email
Screenshot:

How can i make selenium wait till the next page is loaded with same URL and have same fields

I have this code show below:
driver.findElement(By.id("submit")).sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("search-trigger")).sendKeys(Keys.ENTER);
driver.findElement(By.id("search-trigger")).sendKeys("Shampoo");
driver.findElement(By.id("search-trigger")).sendKeys(Keys.ENTER);
I want to search for a product and search option is before and after login page but here i want to do it after login page
I have used
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
but it doesn't work and i cannot use
WebElement “”= driver.findElement(By.id(""));
as the search option is on both pages
and URL remains same after login also
Per my understanding, in short, you want to ensure user has logged in before searching for a product. However u will not be able to use WebElement “”= driver.findElement(By.id(""));
Did you try explicit wait for the presence of username/logout text...etc
WebElement element = wait.until(ExpectedConditions.elementIsVisible(By.id(>someid>)));
Below worked for me, tried searching Samsung after login in flipkart:
public static void f() throws InterruptedException
{
By signin = By.xpath(".//*[#id='container']/div/header/div[1]/div[1]/div/ul/li[9]/a");
Thread.sleep(2000);
By mobile = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[1]/input");
By password = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[2]/input");
By login = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[3]/button");
By myaccount = By.xpath(".//*[#id='container']/div/header/div[1]/div[1]/div/ul/li[8]/a");
By search = By.xpath(".//*[#id='container']/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[1]/div/input");
//geko driver for firefox
System.setProperty("webdriver.gecko.driver", "path of geckodriver.exe");
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.flipkart.com/");
driver.findElement(signin).click();;
driver.findElement(mobile).sendKeys("xxxxxxxxx");
driver.findElement(password).sendKeys("xxxxxxxx");
driver.findElement(login).click();
WebDriverWait wait = new WebDriverWait (driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(myaccount));
driver.findElement(search).sendKeys("samsung");
}

Find Elements by Xpath not giving the correct element in Selenium Webdriver

In the following example, I have to click only for Jet Airways. It appears that the xpath selected is correct since it gives the right only from the selection.
http://i.imgur.com/8TiOgha.png
However when this same is being pulled by Selenium WebDriver, it says element not visible. But it still gives a Button with zero length text string. as given in watch window.
http://i.imgur.com/jrR0221.png
I would appreciate if anyone can help me to point if any error I am making since I am new to VBA
Not sure if your XPath is correct and is locating the right static element...
You may use this for locating 'Jet Airways'
//label[text()[contains(.,'Jet Airways')]]
Also, using .click(), try clicking on the 'Airlines' dropdown before locating the 'Airlines Dropdown' XPath
//span[#title='Airlines']
Update:
public class SkyScanner
{
static String chkBxXpth = "//label[#class='dropdown-item cfx']/input[#checked]";
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
Actions actions = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("http://skyscanner.cntraveller.com/en-GB/flights#/result?originplace=AUH&destinationplace=LHR");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[#title='Airlines']")));
driver.findElement(By.xpath("//span[#title='Airlines']")).click();
List<WebElement> chkBx = driver.findElements(By.xpath(chkBxXpth));
for(WebElement i : chkBx)
{
actions.moveToElement(i).click().perform();
}
driver.findElement(By.xpath("//label[text()[contains(.,'Jet Airways')]]")).click();
}
}