I have written a simple code to enter email in facebook login page. But while entering the email value through sendKeys i am getting validation like "The method sendKeys(String) is undefined for the type By". I have already checked the compliance version which is 1.8. So what is going wrong here??. Below is code snippet:
package SeleniumTests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OpenFacebook {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","geckodriver path");
WebDriver driver=new FirefoxDriver();
driver.get("http:\\facebook.com");
driver.manage().window().maximize();
driver.findElement(By.xpath("//[#id='email']").sendKeys("swarup.wipro#gmail.com");
}
}
I am getting an option of Add cast to By.xpath as a quick fix. Can somebody explain the usage of this or is there any other solution available
As #KoustubhMadkaikar and #AndiCover mentioned, though adding the necessary closing bracket i.e. ) will solve the current issue but as per the best practices you should supply the tagName for your Locator Strategy to be robust and you can use either of the following solutions:
xpath:
driver.findElement(By.xpath("//input[#id='email']")).sendKeys("swarup.wipro#gmail.com");
cssSelector:
driver.findElement(By.cssSelector("input#email")).sendKeys("swarup.wipro#gmail.com");
A closing bracket is missing in your code before .sendKeys
Try following:
driver.findElement(By.xpath("//[#id='email']")).sendKeys("swarup.wipro#gmail.com");
You missed closing round bracket ), use:
driver.findElement(By.xpath("//[#id='email']")).sendKeys("swarup.wipro#gmail.com");
Related
I am trying to compare two values and I wrote the following code that is returning the error below. I'm not a Java Developer and so I do not know how to solve this issue. I tried to find something on the Internet but I couldn't. I appreciate your help.
// import statements begin for selenium imports
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
//import statements end for selenium imports
String formulaTotalQuantity = handl.getExportedValue(“E_CPE_FORMULA__TOTAL_QUANTITY_”);
String orderQuantity = handl.getExportedValue(“E_ORDER_QUANTITY”);
if(orderQuantity.equals(formulaTotalQuantity)){
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
This is the error I am getting when I try to activate the code:
ERROR : illegal character: '\ufffd'/n
I figured out the problem. It was related to the fact that I was using the quotation mark in the wrong manner. I changed it and then the error is gone.
Summary
I want to figure out a way to add a <script> tag into the head of DOM using Selenium's JavascriptExecutor, or any other way of doing this would be nice.
I have tried many ways and also found a few similar topics and none of them solved my problem which is why I felt the need to ask it on here.
For example :
Suggested solutions in this question did not solve my problem. Some people say it worked for them but nope, it didn't for me.
What I've been trying to execute?
Here is the small snippet of the code that I want to execute:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("var s = document.createElement('script');");
jse.executeScript("s.type = 'text/javascript';");
jse.executeScript("s.text = 'function foo() {console.log('foo')}';");
jse.executeScript("window.document.head.appendChild(s);");
I just skipped the code above where you navigate to a webpage using driver.get() etc. and then try to execute the scripts.
Also, s.text would contain the actual script that I want to use so I just put there a foo() function just to give the idea.
The above code throws this error when you run it:
Exception in thread "main" org.openqa.selenium.JavascriptException: ReferenceError: s is not defined
So far I've tried every possible solution I could find on the Internet but none of them seems to work.
OP came up with the following solution:
jse.executeScript("var s=window.document.createElement('script');" +
"s.type = 'text/javascript';" + "s.text = function foo() {console.log('foo')};" +
"window.document.head.appendChild(s);");
For one, this line is invalid.
jse.executeScript("s.text = 'function foo() {console.log('foo')}';");
Note how you wrap single-quote text in single quotes. Use one set as "\""
I would personally do this by doing (edited to make it a global function):
using OpenQA.Selenium.Support.Extensions;
driver.ExecuteJavascript("window.foo = function foo() {console.log('foo')}");
It's as simple as that. You are registering foo as a method by doing this. After you execute this javascript, you can manually go in to the browser developer tools and call "foo()" to check. Additionally, you can check this by registering it directly in the console. Just enter "function foo() {console.log('foo')}" into your browser console, and then call "foo()".
No need to add this as a script tag.
EDIT #2: I fixed my above code suggestion so that the method is assigned to the window, and thus accessible globally, and outside of the anonymous script that javascript executor runs the code in. The original issues with this not working are resolved by this, at least in my testing of it.
I'm going to be starting a new role soon as a Software QA Analyst and I'm trying to practice my automated testing by developing some basic automated test scripts using Java and Selenium WebDriver. I'm very new to automation and Java in general so I wanted to practice using a popular travel website's form as a basis. The script needs to allow for inputting data that's been prepared beforehand in an Excel spreadsheet, capture certain results on the site based off of the input data, and then export those results to the appropriate cell in that same Excel spreadsheet. I've actually created a script that seems to do this fairly well, however every time I run the script, I get an error message that reads:
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
The rest of the script seems to go off pretty smoothly but I'm really not sure what this error is referring to or how to fix it. I went to the URL that it listed but that was like reading a completely foreign language. I've been googling a lot but I have yet to find anything that addresses my specific instance of this error message and I was hoping someone might be able to help me. Most of the script has been assembled by examples I've found online in one form or another and I've assembled it to generally do what I want from it. I'm not sure if this is relevant or not but I have the project loaded with all of the latest versions of the Selenium WebDriver, Apache POI, and Junit, external JAR files. I'm really new to Java, Selenium WebDriver, and automation in general so if anyone has a solution, especially the "why" behind this error, that would be much appreciated. My entire code is below.
package TestCases;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OrbitzDotComBasicFormEntry1 {
public static void main(String[] args) throws Exception {
WebDriver wd = new FirefoxDriver();
String baseURL = "http://www.orbitz.com/";
wd.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
InputStream inp = new FileInputStream("/path/to/spreadsheet/Workbook1.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
String departLocation;
String arriveLocation;
String departureDate;
String returnDate;
int rowcount=sheet.getLastRowNum();
for(int i=1;i<=rowcount;i++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(4);
departLocation=sheet.getRow(i).getCell(0).getStringCellValue();
arriveLocation=sheet.getRow(i).getCell(1).getStringCellValue();
departureDate=sheet.getRow(i).getCell(2).getStringCellValue();
returnDate=sheet.getRow(i).getCell(3).getStringCellValue();
wd.get(baseURL);
//Selects the "Flights Only" radio button
wd.findElement(By.id("search.type.air")).click();
Thread.sleep(1000);
//Enter variable text into the "From" field
wd.findElement(By.name("ar.rt.leaveSlice.orig.key")).click();
wd.findElement(By.name("ar.rt.leaveSlice.orig.key")).clear();
wd.findElement(By.name("ar.rt.leaveSlice.orig.key")).sendKeys(departLocation);
//Enter variable text into the "To" field
wd.findElement(By.name("ar.rt.leaveSlice.dest.key")).click();
wd.findElement(By.name("ar.rt.leaveSlice.dest.key")).clear();
wd.findElement(By.name("ar.rt.leaveSlice.dest.key")).sendKeys(arriveLocation);
//Enter variable text into the "Leave" field
wd.findElement(By.name("ar.rt.leaveSlice.date")).click();
wd.findElement(By.name("ar.rt.leaveSlice.date")).clear();
wd.findElement(By.name("ar.rt.leaveSlice.date")).sendKeys(departureDate);
Thread.sleep(1000);
//Enter variable text into the "Return" field
wd.findElement(By.name("ar.rt.returnSlice.date")).click();
wd.findElement(By.name("ar.rt.returnSlice.date")).clear();
wd.findElement(By.name("ar.rt.returnSlice.date")).sendKeys(returnDate);
Thread.sleep(1000);
//Clicks the "Search Flights" button
wd.findElement(By.name("search")).click();
Thread.sleep(30000);
String bestPrice = wd.findElement(By.cssSelector(".money.small-cents.small-symbol")).getText();
if (cell == null)
cell = row.createCell(4);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(bestPrice);
FileOutputStream fileOut = new FileOutputStream("/path/to/spreadsheet/Workbook1.xlsx");
wb.write(fileOut);
fileOut.close();
}
wd.close();
System.out.println("The Class script has finished running");
}
}
I think LINGS linked a sufficient answer above, this response is more general to your situation and new role. If you are expecting to be working with Selenium I'd take the time to read up on the best and worst practices on the Selenium web pages.
https://seleniumhq.github.io/docs/best.html#best_practices
https://seleniumhq.github.io/docs/worst.html#worst_practices
I'm new to selenium just now started to learn. I'm using chromdriver for my program.
program:
package WebDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SamplePjt {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:\\Users\\YATHEESH\\Desktop\\chromedriver.exe");
WebDriver a = new ChromeDriver ();
a.get("http://cspportal.protechsoftsystems.com");
a.findElement(By.xpath("//*[#id='a_sectionSignIn1']")).click();
a.findElement(By.xpath("//*[#id='txtUserName1']")).sendKeys("auto1#gboxz.com");
a.findElement(By.xpath("//*[#id='txtPinText1']")).sendKeys("test");
a.findElement(By.xpath("//*[#id='Section_SignIn_1']/div[5]/div[2]/input")).click();
a.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
a.findElement(By.xpath("//*[#id='txtLine1Addr']")).sendKeys("123 easy st");
a.findElement(By.xpath("//*[#id='txtCityAddr']")).sendKeys("Little Rock");
a.findElement(By.xpath("//*[#id='txtStateAddr']")).sendKeys("Arkansas");
a.findElement(By.xpath("//*[#id='txtZipCode']")).sendKeys("72211");
a.findElement(By.xpath("//*[#id='txtOfficePhoneNumb']")).sendKeys("9999999999");
a.findElement(By.xpath("//*[#id='divMailingAddress']/div[4]/button")).click();
}
}
I got No such element found, while program read after time out - even though i gave correct xpath,
a.findElement(By.xpath("//*[#id='txtLine1Addr']")).sendKeys("123 easy st");
a.findElement(By.xpath("//*[#id='txtCityAddr']")).sendKeys("Little Rock");
a.findElement(By.xpath("//*[#id='txtStateAddr']")).sendKeys("Arkansas");
a.findElement(By.xpath("//*[#id='txtZipCode']")).sendKeys("72211");
a.findElement(By.xpath("//*[#id='txtOfficePhoneNumb']")).sendKeys("9999999999");
a.findElement(By.xpath("//*[#id='divMailingAddress']/div[4]/button")).click();
Please give me solution for this issue.
You said you are looking for this xpath at this webpage: view-
http://cspportal.protechsoftsystems.com/
I opened this page and got redirected to:
http://cspportal.protechsoftsystems.com/Applications/ServiceProvider/Home/Home.aspx
and after doing a quick check of the source code (CTRL + F for txtLine1Addr) it simply does not find anything with that id.
so your xpath is looking for an id that is not present in source code of the page. But I see that there is a kind of slideshow happening and other javascript stuff on that page, is it possible that the html that you want to test is asynchronously loaded? If so you would have to wait for the presence of those elements first
actually i want to get an element with the #FindBy that is use into the Page Objects pattern.
I've 2 classes, the 1st one is my page objects named TestPage and the 2nd one is named PageSaveTest (where my tests happen and call the TestPage).
I've also tried to use the #FindBy with xpath and id.
>> This is my TestPage
import java.util.List;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class TestPage {
// get autocomplete input
#FindBy(css = "input[id*='supplierOps_input']")
private WebElement autocompleteSupplierOps;
// getter
public WebElement getAutocompleteSupplierOps() {
return autocompleteSupplierOps;
}
}
>> This is my PageSaveTest
// How i "inject" my TestPage
#Page
TestPage testpage;
[...]
// My test
WebElement autocomplete = testpage.getAutocompleteSupplierOps();
String keys = "OP";
autocomplete.sendKeys(keys); // >>>>>>> Error throwed here !
List<WebElement> listSugg = testpage.getSuggestionsSupplierOps();
Error message :
org.openqa.selenium.NoSuchElementException : Returned node was not an HTML element.
My thoughts :
I think the trouble comes from the #FindBy. But i use this example to build my TestPage and my test and this one too.
Question : Can someone explain to me how #FindBy works and be used in my example ? The documentation is really poor about Graphene.
EDIT :
I've modify my getter in TestPage (above), i've tried a simple print of the id attribute value like
public WebElement getAutocompleteSupplierOps() {
System.out.println(">>>> "+autocompleteSupplierOps.getAttribute("id"));
return autocompleteSupplierOps;
}
But still the same error, the #FindBy is f*cked up.
Another #FindBy spec to add in this issue.
Update :
I've fixed my selector but actually there is a probleme with the driver session like :
page2.getAutocompleteSupplierOps();
PAGE 1 ----------------------------------> PAGE 2
driver id:1 ----------------------------------> driver id:2
driver.showPageSource() is empty
return no element found <---------------------- driver.findElement() -> not found
I've used 3 different ways, the #FindBy, the #Drone WebDriver and finally what #Lukas Fryc suggested to me.
Instead of injection of WebElement using #FindBy, you can try using driver directly:
WebDriver driver = GrapheneContext.getProxy(); // this will be removed in Alpha5 version, use `#Drone WebDriver` instead
WebElement autocompleteSupplierOps =
driver.findElement(By.css("input[id*='supplierOps_input']"));
But it should give you the same result as #FindBy do - however it will check that the issue isn't caused by injection, but some other issue is appearing.
You might have wrong CSS selector - support of CSS selectors depends on the used browser and its version.
The node you are trying to find doesn't have to be yet in the page, you might need to wait before it will appear using Waiting API or request guards.
The best practice is usage of remote reusable session and real browser in a development - it can reveal the cause quickly.
I think that instead of using #FindBy(css ="...") you could try #FindBy(xpath="...") I find it a lot more reliable.