In frame, how to find username textbox's xpath with webdriver - java

I want to sign in to http://www.timesjobs.com/. Upon signing in a pop-up appears (it is the css lightbox). Cannot find the exact xpath for the username on this sign-in box. I iterated over each and every frame and tried to use firefox generated xpath for username textbox. I got exception as:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//html/body//input[#name='j_username']"}.
Tried below code but no luck:
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
driver.get("http://www.timesjobs.com");
driver.findElement(By.linkText("Sign In")).click();
Thread.sleep(10000L);
List<WebElement> frames = driver.findElements(By.tagName("iframe"));
System.out.println("Total Frames: " + frames.size());
int k =0;
while(k<=frames.size()){
try{driver.switchTo().defaultContent();
driver.switchTo().frame(k);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement we1 = driver.findElement(By.xpath("//html/body//input[#name='j_username']"));
we1.sendKeys("xyzusername#xyzcompany.com");
System.out.println("in try BLOCK:"+k);
}catch(Exception e){
e.printStackTrace();
System.out.println("in catch: "+k);
}finally{
k++;}
}
System.out.println("end of the program");
}

Try the following code. It works.
Your username Field is contained within GB_Frame which is contained under GB_Frame1. So we have to switch to GB_Frame1 and then to GB_Frame. Username field has a name, so better use it over xpath.
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.timesjobs.com");
driver.findElement(By.linkText("Sign In")).click();
Thread.sleep(10000);
driver.switchTo().frame("GB_frame1");
driver.switchTo().frame("GB_frame");
WebElement we1 = driver.findElement(By.name("j_username"));
we1.sendKeys("xyzusername#xyzcompany.com");
}
I dont understand what difficulty you had in identifying the frames. It was pretty clear from the page source. Let me know if this helps you.

Related

Using DataProvider by initializing WebDriver one time within TestNG

I'm trying to check login page control by using dataprovider but i don't want to initialize webdriver again and again for each username password control. Once i come into login page, checking all concerned scenarios on login page in single time without starting another driver seems more convenient to me but i couldn't figure it out. When running following code, data[0][0] and data[0][1] is being correctly checked but it gives no such element on Login method having second priority test annotation when being tried to be typed data[1][0] and data[1][1]. Probably, it causes because driver is not looking at that page on that time. How can I handle this issue ?
error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#class='q-input-wrapper email-input']//input[#class='q-input']"}
code:
public class TestCaseFirst {
public WebDriver driver;
#BeforeTest
public void Start() throws InterruptedException {
WebDriverManager.chromedriver().setup();
driver= new ChromeDriver();
driver.get("https://www.faxzas.com/");
driver.manage().window().maximize();
Thread.sleep(2000);}
#Test(priority=1)
public void RoadtoLogin() throws InterruptedException {
driver.findElement(By.xpath("//a[#title='Close']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='login-container']//span[#id='not-logged-in-container']")).click();;
Thread.sleep(1000);
}
#Test(dataProvider="loginInfos", priority=2)
public void Login(String mail, String password) throws InterruptedException {
driver.findElement(By.xpath("//div[#class='q-input-wrapper email-input']//input[#class='q-input']")).sendKeys(mail);
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='q-input-wrapper']//input[#class='q-input']")).sendKeys(password);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#type='submit']")).click();
Thread.sleep(1000);
String description = driver.findElement(By.xpath("//div[#id='error-box-wrapper']//span[#class='message']")).getText();
System.out.println(description);
}
#DataProvider(name="loginInfos")
public Object[][] getData(){
Object[][] data = new Object[6][2];
data[0][0]="blackkfredo#gmail.com";
data[0][1]="";
data[1][0]="blackkfredo#gmail.com";
data[1][1]="443242";
data[2][0]="";
data[2][1]="1a2b3c4d";
data[3][0]="";
data[3][1]="";
data[4][0]="blackkfredogmail.com";
data[4][1]="1a2b3c4d";
data[5][0]="blackkfredo#gmail.com";
data[5][1]="1a2b3c4d";
return data;
}
}
You need to reset your page to the login page where you are expecting the element to be. Either put an #AfterMethod and go back to the page you are trying to test or put an #BeforeMethod for the same. You may even want to wrap up your find element calls and handle the exceptions by going back to the main page.

Prompting user input in selenium web driver before launching URL

I am trying to take user input then stored into the variable and i want to use that input into my program .
Here is my code , code is asking for user input but not loading the URL . It is just initiating the driver. Please someone correct me .
Current behavior:
Initiating the driver (IE shows the message " This is the Initial start page for wendriver server"
Asking for prompt .I gave my input in the prompt and click OK.
thats it .. after that code is not getting executed. Please help me
enter image description here
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
if(isAlertPresent(driver)) {
// switch to alert
Alert alert = driver.switchTo().alert();
// sleep to allow user to input text
Thread.sleep(10000);
// this doesn't seem to work
alert.accept();
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
.......
......
// some more code which is doing my application fucntionality
.......
......
........
private static boolean isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
}
}
}
If you need to take input (ie. URL) from promp then you may use JOptionPane's showInputDialog() method from Java Swing.
Code snippet:
String URL =JOptionPane.showInputDialog(null,"Enter URL");
Try following code; it should serve your purpose:
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
isAlertPresent(driver);
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
}
private static void isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // even though not needed
isAlertPresent(driver);
} // try
catch (NoAlertPresentException Ex)
{
}
}
}

I am getting nullpointer exception when I perform click() for the same WebElement which I have performed earlier in my Code

I am getting some good handson on my Java ans Selenium. When I use the same "Input_Search_Box" Webelement to perform click method it throws a nullpointer exception. I have googled and tried few work around like adding Thread, adding Explicit wait but still no clue where i miss. Any suggestion would be greatly appreciated.
Here is my Code:
public class Testclass {
WebElement Input_Search_Box;
WebDriver driver;
#Test
public void openBrowser() throws Exception{
System.setProperty("webdriver.chrome.driver","E:\\Ecilpse\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://en.wikipedia.org/wiki/Main_Page");
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.manage().window().maximize();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,500)");
WebElement Click_Create_Book = driver.findElement(By.xpath(".//*[#id='coll-create_a_book']/a"));
Click_Create_Book.click();
WebElement Start_Book_Creator_Btn = driver.findElement(By.xpath(".//*[#id='mw-content-text']/form/div/div[1]/button"));
Start_Book_Creator_Btn.click();
Input_Search_Box = driver.findElement(By.xpath(".//*[#id='searchInput']"));
Input_Search_Box.click();
Input_Search_Box.sendKeys("Selenium",Keys.ENTER);
for(int i =0;i<=8;i++){
try{
if(driver.findElement(By.xpath(".//*[#id='siteNotice']/div[2]/div[2]/div")).isDisplayed())
break;
}
catch(Exception e){
jse.executeScript("window.scrollBy(0,2500)");
}
}
for(int j=0;j<=5;j++){
if(driver.findElement(By.id("coll-add_article")).isDisplayed()) {
System.out.println("If Executed");
break;
}else
{
WebElement Book_Remove = driver.findElement(By.xpath(".//*[#id='coll-remove_article']"));
Book_Remove.click();
}
}
WebElement Add_This_Book = driver.findElement(By.xpath(".//*[#id='coll-add_article']"));
Add_This_Book.click();
Thread.sleep(3000);
for(int k =0;k<=6;k++){
jse.executeScript("window.scrollBy(0,-2500)");
Thread.sleep(3000);
}
Thread.sleep(4000);
System.out.println("Sctipr on hold for 4k seconds");
//Here is the Nullpointer error occuring
Input_Search_Box.click();
Input_SearchBox.sendKeys("JSCRIPT",Keys.ENTER);
}
}
If the page has changed/reloaded then you need to use find again.
Sometimes on user actions the page can trigger calls that can change the page that can change the state of the page and the current found objects are lost this can results in a stale element exception or null exception.

Selection of data from Yahoo search bar using csselector fails

package p111;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Yahoo_c {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Above is the code.
When i run this, execution goes until "pizza" being entered into yahoo search.Later with no error message in console execution terminates.
The error image is
Please help resolve this issue.Am trying to select pizza delivery from list.
You can try Name instead of path as the yahoo search has a name for selenium to work with. Please let know if Xpath is must for you to work then i will change my code.
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.name("p"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Or you can use the same by ID
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.id("UHSearchBox"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
The option you are trying to click is a link in <a> anchor tag.. you can simply use By.linkText if you are specific on the link.
driver.findElement(By.linkText("pizza delivery")).click();
Problem is that you are sendKeys, even though the pizza is typed but the drop-down list does not appears because sendKeys is not equivalent of typing through keyboard. Work around is simple. You need to perform a keyboard action after writing "pizza".
// type pizza
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
// now perform keyboard action (of pressing space key)
wi.findElement(By.xpath("String")).SendKeys(Keys.Space);
// now click on the pizza delivery link
wi.findElement(By.linkText("pizza delivery")).click();
Try above code in your project, after adding proper wait and with correct element locators.
Try this xpath //*[contains(text(),'pizza delivery')]
It'll work! :)
Check this in firepath and make sure you get only one node with the locator.

"Unable to locate element" exception with WebDriver

I'm getting an "Unable to locate element" exception while running the below code. My expected output is First Page of GoogleResults.
public static void main(String[] args) {
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
WebElement oSearchField = driver.findElement(By.name("q"));
oSearchField.sendKeys("Selenium");
WebElement oButton = driver.findElement(By.name("btnG"));
oButton.click();
//String oNext = "//td[#class='b navend']/a[#id='pnnext']";
WebElement oPrevious;
oPrevious = driver.findElement(By.xpath("//td[#class='b navend']/a[#id='pnprev']"));
if (!oPrevious.isDisplayed()){
System.out.println("First Page of GoogleResults");
}
}
If I run the above code I get "Unable to Locate Element Exception". I know the Previous Button Element is not in the first page of the Google Search Results page, but I want to suppress the exception and get the output of the next step if condition.
Logical mistake -
oPrevious = driver.findElement(By.xpath("//td[#class='b navend']/a[#id='pnprev']"));
will fail or give error if WebDriver can't locate the element.
Try using something like -
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
You can pass the xpath to the function like
boolean x = isElementPresent(By.xpath("//td[#class='b navend']/a[#id='pnprev']"));
if (!x){
System.out.println("First Page of GoogleResults");
}

Categories

Resources