I am trying to create webdriver object reference in the class which is not having main method. it is not allowing me to create the object. Finally, I tried with an instance and it is not working(not identifying driver)
public class LoginPage
{
public static WebDriver driver;
static ResourceLoader loader = new ResourceLoader();
public static String loginVerify(String username, String password)
{
System.out.println("navigated to loginvarify() :: ");
logger.info("username is "+username);
logger.info("password is "+password);
try
{
driver.findElement(By.id(loader.getProperty(Constants.UserName))).sendKeys(username);
}
Please help me
public class LoginPage
{
System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/osx/chromedriver"); // path to your chrome driver
public static WebDriver driver = new ChromeDriver();
static ResourceLoader loader = new ResourceLoader();
public static String loginVerify(String username, String password)
{
System.out.println("navigated to loginvarify() :: ");
logger.info("username is "+username);
logger.info("password is "+password);
try
{
driver.findElement(By.id(loader.getProperty(Constants.UserName))).sendKeys(username);
}
I have updated your code, kindly refer you are missing your driver initialization. I have initialized to chromeDriver(), if you are using firefox initialize it accordingly.
System.setProperty("webdriver.chrome.driver",
"src/main/resources/drivers/osx/chromedriver"); // path to your chrome
driver
If you are not having the chrome driver, kindly download and place it in your directory path and pass the path reference accordingly.
https://sites.google.com/a/chromium.org/chromedriver/downloads
Let me know if you still face any issue or anything is not clear.
WebDrvier driver = new FireFoxDriver(); //driver initialization
driver.FindElement(By.Id(IdName)); //to find elements by ID in UI
You can define your chrome driver path using System.setProperty("webdriver.chrome.driver", "C:\Spring Workspace\chromedriver\chromedriver.exe"); // path to your chrome driver or you can define the path in the environment variable so you don't have to use this setProperty code again and again......if you are using firefox driver than not need to define any setProperty beacause it is already defined inside org.openqa.selenium.firefox.FirefoxDriver....
Related
I am trying to generate a jar file of my test to use it in JMeter, I am trying this solution How to make an executable jar file using IntelliJ from a Selenium/TestNG java file? but the problem in on step 4.
4- Select your main class using the browse button.
When I search for class I can't select mine .java code, how I can do the step 4 possible?
My code
public class Jmeter {
WebDriver driver = null;
#Test
public void testLoad() {
// Robot robot = new Robot();
ChromeOptions options = new ChromeOptions();
options.addArguments(Arrays.asList("disable-infobars", "ignore-certificate-errors", "start-maximized","use-fake-ui-for-media-stream"));//
System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver.exe");
WebDriver driver = new ChromeDriver(options);
driver.get("myurl");
my commands
}
}
Does someone know how to solve this?
Solution
I created a class with the main method to call my test.
package Jmeter;
public class JmeterMain {
public static void main(String[] args) {
Jmeter test = new Jmeter();
test.testLoad();
}
}
I've been trying to implement headless browser to my tests and I'm getting an error message that shows me this: "Unable to locate element: {"method":"id","selector":"my_id"}". This is the code that I'm working with:
[TestFixture]
class ClientesSystemTest
{
private ChromeOptions options;
private NewClientesPage page;
private IWebDriver driver;
public ClientesSystemTest()
{
options = new ChromeOptions();
options.AddArgument("--headless");
driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options);
page = new NewClientesPage(driver);
}
[Test]
public void CadastraCliente()
{
page.Visita();
page.Cadastra("Paulo", "Guedes", "00870021087", "Rua abcdwxyz, 14", 15);
driver.Close();
}
}
and this is the Cadastra method.:
public void Cadastra(string nome, string sobrenome, string cpf, string endereco, int idade)
{
IWebElement nomeCliente = driver.FindElement(By.Id("Nome"));
IWebElement sobrenomeCliente = driver.FindElement(By.Id("Sobrenome"));
IWebElement cpfCliente = driver.FindElement(By.Id("CPF"));
IWebElement enderecoCliente = driver.FindElement(By.Id("Endereco"));
IWebElement idadeCliente = driver.FindElement(By.Id("Idade"));
IWebElement estadoCivilCliente = driver.FindElement(By.Name("EstadoCivil"));
driver.FindElement(By.CssSelector("[value=Divorciado]")).Click();
nomeCliente.SendKeys(nome);
sobrenomeCliente.SendKeys(sobrenome);
cpfCliente.SendKeys(cpf);
enderecoCliente.SendKeys(endereco);
idadeCliente.SendKeys(idade.ToString());
nomeCliente.Submit();
}
I've tried everything by this point. The test runs normally without the headless feature. Does anyone have a solution for this error? Thanks.
My guess would be that your site shows different elements depending on the browser resolution. Typically the headless browser is a smaller setting so I'd make sure it's set to the same size you use when you test non-headless.
how is possible to find the xpath for an angularJs element? for instance i discovered that all links in my page have the same xpath due to the repeated items in angularJs -->
.//*[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a
but i have 10 of element , they are differente for text, so i tried with `"
so i tried with contains but it never find it
.//[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(#aria-label='Creazione Prodotto')]"`
i use selenium, junit4 , firefox webDriver
this is my code
public class PB01_TTT {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
WebElement element;
#Before()
public void setUp() throws Exception {
FirefoxProfile fxProfile = new FirefoxProfile();
fxProfile.setPreference("browser.download.folderList", 2);
fxProfile.setPreference("browser.download.manager.showWhenStarting", false);
fxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
fxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/pdf, application/x-pdf, application/octet-stream");
fxProfile.setPreference("pdfjs.disabled", true);
driver = new FirefoxDriver(fxProfile);
baseUrl = "https://w8aon2bpm.replynet.prv:9443";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testPBO1TTT() throws Exception {
driver.get(baseUrl + "/ProcessPortal/login.jsp");
// driver.get(baseUrl + "/ProcessPortal/dashboards/SYSRP/RESPONSIVE_WORK");
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("user");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("password");
String columnToDisplay=driver.findElements(By.xpath(".//*[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(#aria-label='Creazione Prodotto')]"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
element = (WebElement) driver.findElements(By.xpath(columnToDisplayXpath));
Assert.assertNotNull(element);
it always return me a notFoundElement, any suggestions ?
Thank you
If you have 10 links, then there is a high chance they are different in a way even if the path is the same, in this case you need to construct an path based on the thing that is different.
For example: use href, text or other any part that differs
//a[contains(#href, 'part_of_href')]
//a[contains(text(), 'part_of_text')]
//a[#title='title']
//a[contains(#aria-label='Creazione Prodotto')]
If you need any help in getting the selector please add the html section of the links, you can change the url if needed.
Tip: avoid using absolute xpaths and attributes that do not suggest anything and they can change like: .//*[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(#aria-label='Creazione Prodotto')]"
This will give you a lot of work in the future.
I am researching how to set an individual profile using RemoteWebDriver. I have been reading about it on the following thread.
http://stackoverflow.com/questions/12961037/parallel-execution-of-firefoxdriver-tests-with-profile-share-same-profile-copy
I am trying to tackle it as following:
public static RemoteWebDriver getDriver(String methodName) throws MalformedURLException {
String SELENIUM_HUB_URL = "http://localhost:4444/wd/hub";
ThreadLocal<RemoteWebDriver> remoteWebDriver = null;
File currentProfileFile = new File(methodName);
//This is where it gives the error
FirefoxProfile currentFireFoxProfile = new FirefoxProfile(currentProfileFile);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(FirefoxDriver.PROFILE, currentFireFoxProfile);
String proxy = System.getProperty("proxy");
try {
remoteWebDriver = new ThreadLocal<RemoteWebDriver>();
remoteWebDriver.set(new RemoteWebDriver(new URL(SELENIUM_HUB_URL),
capabilities));
} catch (MalformedURLException e) {
System.out.println("Please fix the RemoteDriverSetup.class");
}
remoteWebDriver.get().manage().window()
.setSize(new Dimension(2880, 1524));
remoteWebDriver.get().manage().timeouts()
.pageLoadTimeout(10, TimeUnit.SECONDS);
remoteWebDriver.get().manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
return remoteWebDriver.get(); // Will return a thread-safe instance of the WebDriver
}
I am getting the following error :
Time elapsed: 1.044 sec <<< FAILURE!
org.openqa.selenium.firefox.UnableToCreateProfileException: Given model profile directory does
not exist: TEST001
Update : I am injecting method name in the BaseTest class below
#BeforeMethod
public void startTest(Method testMethod) {
LOG.info("Starting test: " + testMethod.getName());
this.driver = WebDriverSetup.getDriver(testMethod.getName());
}
If you don't want to customize anything on your Firefox profile, better to create Firefox webdriver instance by NOT providing any profile details (as mentioned by Nguyen).
If you really want to create separate profiles (may be required to install some plug-ins like Firebug), in that case, you can do that by without passing any file name as below:
FirefoxProfile currentFireFoxProfile = new FirefoxProfile();
//Do some customization - add extension
currentFireFoxProfile.addExtension(pathOfextensionToInstall);
//or Setup some Firefox config. switch values
currentFireFoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
In the Selenium docs I can see how to take a normal screenshot:
http://seleniumhq.org/docs/04_webdriver_advanced.html
But I would like to use captureentirepagescreenshot with a remote webdriver, C#
Is this possible? any examples?
Please use selenium webdriver version 2.33. Below code is a c# code so please download selenium webdriver dlls for .net from link http://docs.seleniumhq.org/download/
Selenium webdriver has inbuilt function called ITakesScreenshot to take screenshot runtime.
Please see below code
`public static void SaveScreenShot(string screenshotFirstName)
{
var folderLocation = "Screenshot folder path";
var screenshot = ((ITakesScreenshot)Driver).GetScreenshot();
var filename = new StringBuilder(folderLocation);
filename.Append(screenshotFirstName);
filename.Append(DateTime.Now.ToString("dd-MM-yyyy HH_mm_ss"));\\append date and time
filename.Append(".png"); \\append image extension
screenshot.SaveAsFile(filename.ToString(), System.Drawing.Imaging.ImageFormat.Png);
}`
Hope this will work for you.
Thanks,
Anshul
If you use a IWebDriver implementation (such as InternetExplorerDriver, FirefoxDriver) you can simply cast it to a ITakesScreenshot interface and use the GetScreenShot() method:
IWebDriver driver = new InternetExplorerDriver();
Screenshot screenShot = ((ITakesScreenshot)driver).GetScreenshot();
screenShot.SaveAsFile(/*fullFileNameAndPath*/, ImageFormat.Png);
But if you want to to do this with a RemoteWebDriver you can't, because it doesn't implement the ITakesScreenshot interface. So, you have to create a new class based on RemoteWebDriver that implements this interface and adds the GetScreenshot() method such as:
public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
{
public ScreenShotRemoteWebDriver(Uri RemoteAdress, ICapabilities capabilities)
: base(RemoteAdress, capabilities) { }
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
// Get the screenshot as base64.
Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
string base64 = screenshotResponse.Value.ToString();
// ... and convert it.
return new Screenshot(base64);
}
}
Now you can use it as you would for a IWebDriver:
RemoteWebDriver driver = new ScreenShotRemoteWebDriver(/*uri*/, /*capabilities*/);
Screenshot screenShot = ((ITakesScreenshot)driver).GetScreenshot();
screenShot.SaveAsFile(/*fullFileNameAndPath*/, ImageFormat.Png);
It took me sometime to understand the maze of classes and interfaces for the drivers as well, but after a while it all makes sense.