I am try to test the login function using selenium but I get this exception :
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#name='Guichet']"}
this my code :
public class LoginTest {
public static WebDriver driver;
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.chrome.driver", "C:\\driver\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//driver.manage().window().maximize();
}
#BeforeMethod
public void openBrowser() {
driver.get("http:url");
System.out.println("We are currently on the following URL" +driver.getCurrentUrl());
}
#Test(description="This method validates the login functionality")
public void loginFunction() {
//WebDriverWait gui = new WebDriverWait(driver,100);
//Locating the email field element via Name tag and storing it in the webelement
WebElement guichet = driver.findElement(By.xpath("//input[#name='Guichet']"));
WebElement matricule = driver.findElement(By.name("Matricule"));
WebElement password = driver.findElement(By.name("Mot_de_passe"));
WebElement save = driver.findElement(By.name("Valider"));
//Entering text into the email field
guichet.sendKeys("0000");
matricule.sendKeys("login");
password.sendKeys("password");
save.click();
}
#AfterMethod
public void postLogin(){
System.out.println(driver.getCurrentUrl());
Assert.assertEquals(driver.getCurrentUrl(), "http:url.html");
}
#AfterClass
public void afterClass(){
//driver.quit();
}
}
NB : I tried to use the and xpath but still does not work also I try to using some solution in this Post but no result
This the Html page Using the frame for menu and other form login pages
SCT
:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META name="GENERATOR" content="">
<META http-equiv="Content-Style-Type" content="text/css">
<TITLE>
</TITLE>
<LINK href="Master.css" rel="stylesheet" type="text/css">
</HEAD>
<FRAMESET rows="14%,78%" frameborder="NO" border="0">
<FRAME src="menu.html" scrolling="NO" name="entete">
<FRAME src="SCT.html">
<NOFRAMES>
<BODY BGCOLOR="#FFFFFF">
<P>L'affichage de cette page requiert un navigateur prenant en charge les
cadres.</P>
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>
driver.switchTo().frame(0);
WebElement guichet = driver.findElement(By.xpath("//input[#name='Guichet']"));
WebElement matricule = driver.findElement(By.name("Matricule"));
WebElement password = driver.findElement(By.name("Mot_de_passe"));
WebElement save = driver.findElement(By.name("Valider"));
//Entering text into the email field
guichet.sendKeys("0000");
matricule.sendKeys("login");
password.sendKeys("password");
save.click();
driver.switchTo().defaultContent();
Related
I would like to click on checkbox but it keep saying that element is not interactable.
I actually tried .click, javascriptexecutor, actions, wait until, thread.sleep, scroll. Even when I try context click on the checkbox it says that element is not interactable.
Any other ideas?
<div class="panel panel-default">
<div class="panel-heading">Single Checkbox Demo</div>
<div class="panel-body">
<p> Clicking on the checkbox will display a success message. Keep an eye on it</p>
<div class="checkbox">
<label>
<input type="checkbox" id="isAgeSelected" value="">Click on this check box</label>
</div>
<div id="txtAge" style="display:none">Success - Check box is checked</div>
</div>
</div>
and here is the url: https://www.seleniumeasy.com/test/basic-checkbox-demo.html
Checkbox code:
#FindBy(id = "isAgeSelected")
private WebElement checkboxFirstExample;
public checkboxDemo checkboxFirstEx(){
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].scrollIntoView();", checkboxFirstExample);
executor.executeScript("arguments[0].click();", checkboxFirstExample);
return this;
}
Whole code:
public class checkboxDemo extends baseSeleniumClass {
#FindBy(xpath = "//ul[#id='treemenu']//a[contains(text(),'Input Forms')]")
private WebElement inputFormsMenu;
#FindBy(xpath = "//li[#style='display: list-item;']//a[#href='./basic-checkbox-demo.html']")
private WebElement checkboxDemo;
#FindBy(id = "isAgeSelected")
private WebElement checkboxFirstExample;
#FindBy(xpath = "//div[#id='txtAge']")
private WebElement ageSelected;
#FindBy(xpath = "//input[#type='button'][#id='check1']")
private WebElement checkboxAll;
private seleniumHelper helper;
private WebDriver driver;
public checkboxDemo(WebDriver driver){
PageFactory.initElements(driver, this);
this.helper = new seleniumHelper(driver);
this.driver = driver;
}
public checkboxDemo checkboxDemostart(){
checkboxDemo.click();
return this;
}
public checkboxDemo checkboxFirstEx(){
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].scrollIntoView({block: 'center'});", checkboxFirstExample);
checkboxFirstExample.click();
System.out.println("3. " + ageSelected.getText() + " - First checkbox passed");
return this;
}
public checkboxDemo checkboxSecondEx(){
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].scrollIntoView();", checkboxAll);
executor.executeScript("arguments[0].click();", checkboxAll);
System.out.println("4. " + checkboxAll.getAttribute("value") + " - All checkboxes are selected");
return this;
}
public checkboxDemo inputMenu(){
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", inputFormsMenu);
return this;
}
}
#FindBy(id = "isAgeSelected")
private WebElement checkboxFirstExample;
public checkboxDemo checkboxFirstEx(){
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].scrollIntoView({block: \"center\"});", checkboxFirstExample);
checkboxFirstExample.click();
return this;
}
use id , 'isAgeSelected' . You should click the input tag
xpath :
//input[#id="isAgeSelected"]
CSS:
input[id="isAgeSelected"]
When I use POM class, getting Nullpointer exception. however if I use driver.findelement directly in class, it works correct. Can you please pour in your thougts to fix this?
#Test
public void testFlow() throws InterruptedException {
UtilityClass.setUpPath();
WebDriver driver = new ChromeDriver();
try{
driver.navigate().to("http://demo.guru99.com/payment-gateway/check_credit_balance.php");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("card_nmuber")).sendKeys("1234567891234567");
System.out.println(driver.findElement(By.id("card_nmuber")).getAttribute("value"));
HomePage hp = new HomePage(driver);
hp.clickSubmit();
}
finally{
driver.quit();
}
}
public class HomePage {
WebDriver driver;
public HomePage(WebDriver driver){
this.driver = driver;
}
#FindBy(name = "submit")
private WebElement signIn ;
public void clickSubmit() {
signIn.click(); }} }}
Error: java.lang.NullPointerException
Your page object field is not associated with a WebElement. You need to add a constructor that would call
PageFactory.initElements(driver, this)
Your constructor of course has to take WebDriver as an argument
In HomePage class:
By signIn = By.name("submit");
public void clickSubmit() {
driver.findElement(signIn).click(); }}
Found the correct way of using POM without Page factory. This is working code
My class 1 is 'Login'
My class 2 is 'checkout'
To run a class 2(checkout), I have to first log in(class 1) so my class 2 is dependent on class 1. But when I run the below code, a blank chrome screen is shown:
Chrome browser
The chrome driver is not going to the URL I have provided it just stuck with the blank screen.
My class 1 is a login class and to do a checkout, I need to first login so when I am doing that its not working.
Please let me know whats the mistake I am doing here?
Class 1 code:
package testcases;
public class Login{
static WebDriver driver= new ChromeDriver();
#BeforeClass
public void init() {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("URL");
}
#Test
public static void testcase1()
{
driver.findElement(By.xpath(".//*[#id='email']")).click();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("testid#g.com");
driver.findElement(By.xpath(".//*[#id='password']")).click();
driver.findElement(By.xpath(".//*[#id='password']")).sendKeys("3222"); driver.findElement(By.xpath("/html/body/div[4]/div/form/div[3]/div[2]/button")).click();
}
Class 2 code:
public class checkout {
static WebDriver driver= new ChromeDriver();
#BeforeClass
public void init() {
driver.manage().window().maximize();
driver.get("URL");
}
#Test(dependsOnMethods={"com.test.Login.testcase1"})
public void checkout() throws InterruptedException{
System.out.println("test");
driver.quit(); }}
testng.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none" preserve-order="true">
<test name="Test">
<classes>
<class name="com.test.Login"/>
<class name="com.test.checkout"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Errors:
Errors
Could please update Chrome Driver and Chrome Browser to latest and retry and confirm
Chrome browser launches with blank page in Selenium webdriver
I am not sure whether you are following Page Object model or not.
You need to make changes accordingly :
There is no need to create instance of WebDriver in check out class. You can just pass the reference of driver from Login Class.
You need to set the path of chromeDriver before launching it.
You can introduce Groups and dependsOnGroups concept. Make testcase1() in a group which is present in Login class and make checkout() method as depends on groups by introducing dependsOnGroups concept.
Here you can follow this code :
Login.java
public class Login {
static WebDriver driver;
#BeforeClass
public void init() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user***\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
}
#Test(groups={"Login.testcase1"})
public static void testcase1()
{
driver.findElement(By.xpath(".//*[#id='email']")).click();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("testid#g.com");
driver.findElement(By.xpath(".//*[#id='password']")).click();
driver.findElement(By.xpath(".//*[#id='password']")).sendKeys("3222");
driver.findElement(By.xpath("/html/body/div[4]/div/form/div[3]/div[2]/button")).click();
getCheckoutPage(driver);
}
public static CheckOut getCheckoutPage(WebDriver driver) {
return new CheckOut(driver);
}
}
Checkout.java
public class CheckOut {
private WebDriver driver;
public CheckOut(WebDriver driver) {
this.driver = driver;
}
#Test(dependsOnGroups={"Login.testcase1"})
public void checkout() throws InterruptedException{
System.out.println("test");
driver.quit(); }
}
I use the :contains() method but I get the error below:
Test Name: TheMahler3Test
Test FullName: TestingCssSelector.Mahler3.TheMahler3Test
Test Source: c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs : line 50
Test Outcome: Failed
Test Duration: 0:00:05.135
Result Message: System.InvalidOperationException : An invalid or illegal string was specified
Result StackTrace:
at OpenQA.Selenium.Support.UI.DefaultWait1.PropagateExceptionIfNotIgnored(Exception e)
at OpenQA.Selenium.Support.UI.DefaultWait1.Until[TResult](Func`2 condition)
at TestingCssSelector.Mahler3.TheMahler3Test() in c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs:line 59
This is the page's source code:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<div id="myDiv">
<select name="mySelectInput">
<option value="">Select one...</option>
<option value="1">AT&T</option>
<option value="2">TMobile</option>
</select>
</div>
</div>
</body>
</html>
And this is the WebDriver C# code:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
namespace TestingCssSelector
{
[TestFixture]
public class Mahler3
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[SetUp]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "http://localhost:49638/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheMahler3Test()
{
driver.Navigate().GoToUrl(baseURL + "/");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(40));
wait.Until(d =>
{
return driver.FindElement(By.XPath("/html/body/div/div/select"));
});
driver.FindElement(By.XPath("/html/body/div/div/select")).Click();
wait.Until(d =>
{
return driver.FindElement(By.CssSelector("option:contains('AT&T')"));
});
driver.FindElement(By.CssSelector("option:contains('AT&T')")).Click();
// ERROR: Caught exception [ReferenceError: selectLocator is not defined]
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText()
{
try
{
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert)
{
alert.Accept();
}
else
{
alert.Dismiss();
}
return alertText;
}
finally
{
acceptNextAlert = true;
}
}
}
}
contains is not part of the CSS selector specification and is therefore not going to work.
The contains selector we all know and love comes from Sizzle, the CSS-selector engine behind jQuery. Unless you wish to physically load Sizzle or jQuery into your page, then you are not going to be able to use your current solution.
The only real way of doing text-based searching is using XPath, or find a list of elements (using anyway you like) and filtering them within code.
For your basic page, it's easy enough to simply select it by ID, so simply:
Select select = new Select(driver.FindElement(By.Id("mySelectInput")));
You would then select it by using:
select.SelectByVisibleText("AT&T");
I have a servlet which is supposed to process uploaded file. Apache common file upload library is used for that.
The problem is that file comes corrupted. Looks like symbols "~" are replaced on "?" in the file.
Here my html form is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<FORM action="http://localhost:8081/wihome-connector-bpm/bpmFileUpload"
enctype="multipart/form-data"
method="post">
What files are you sending?
<INPUT type="file" name="uploadedFiles"><BR>
<INPUT type="submit" value="Send">
<INPUT type="reset">
</FORM>
</body>
</html>
And that is the servlet:
public class FileUploadServlet extends HttpServlet {
private static final Log LOG = LogFactory.getLog(FileUploadServlet.class);
/**
* {#inheritDoc}
*/
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
LOG.info("Uploading file: " + item.getName());
byte[] fileContents = IOUtils.toByteArray(item.getInputStream());
//...
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to upload image
But instead I get that:
Can you please help me? What can be the problem?
Ok, there was a problem with filters. Project had a filter that currupted request before it rich servlet.