when i select values hidden its showing error as:
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Unable to locate element: {"method":"partial link
text","selector":"vehicle-make"}
Here is my code:
package section5.advWays.locatingObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class CusXPathUsingAtt1 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver wd = new FirefoxDriver();
wd.manage().window().maximize();
Thread.sleep(5000); wd.get("http://www.tirerack.com/content/tirerack/desktop/en/homepage.html");
Select SelectMakedropdown = new Select(wd.findElement(By.id("vehicle-make")));
SelectMakedropdown.selectByVisibleText("BMW");
Select YearSelectDropdown = new Select(wd.findElement(By.id("vehicle-year")));
YearSelectDropdown.selectByVisibleText("2011");
Select VehicleSelectDropdown = new Select(wd.findElement(By.id("vehicle-model")));
VehicleSelectDropdown.selectByVisibleText("228i xDrive Coupe");
}
}
How to select those dropdown using selenium webdriver?
There are two things:
I found that you first need to click on an element without which the Select menu won't open. So in my code, I'm first clicking on the element to enable select menu.
There are also some elements that aren't readily available. Say, for example the Year won't get enabled unless Make is entered.
Please see the code below:
WebDriver driver= new FirefoxDriver();
driver.get("http://www.tirerack.com/content/tirerack/desktop/en/homepage.html");
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Select Make')]")));
driver.findElement(By.xpath("//div[contains(text(),'Select Make')]")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("vehicle-make")));
Select SelectMakedropdown = new Select(driver.findElement(By.id("vehicle-make")));
SelectMakedropdown.selectByVisibleText("BMW");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Select Year')]")));
driver.findElement(By.xpath("//div[contains(text(),'Select Year')]")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("vehicle-year")));
Select YearSelectDropdown = new Select(driver.findElement(By.id("vehicle-year")));
YearSelectDropdown.selectByVisibleText("2011");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Select Model')]")));
driver.findElement(By.xpath("//div[contains(text(),'Select Model')]")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("vehicle-model")));
Select VehicleSelectDropdown = new Select(driver.findElement(By.id("vehicle-model")));
VehicleSelectDropdown.selectByVisibleText("128i Cabriolet Base Model");
driver.quit();
UPDATE for Firefox:
I tried a lot, but I'm still unable to identify why isn't the selects working in Firefox. But I still managed to come up with a work around to do the needful. Here I'm using less use of clicks and more of features your application supports.
WebDriver driver= new FirefoxDriver();
driver.get("http://www.tirerack.com/content/tirerack/desktop/en/homepage.html");
WebDriverWait wait = new WebDriverWait(driver, 30);
JavascriptExecutor executor = (JavascriptExecutor) driver;
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Select Make')]")));
WebElement we1 = driver.findElement(By.xpath("//div[contains(text(),'Select Make')]"));
executor.executeScript("arguments[0].click();", we1);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("vehicle-make")));
WebElement SelectMakedropdown = driver.findElement(By.id("vehicle-make"));
SelectMakedropdown.sendKeys("BMW");
SelectMakedropdown.sendKeys(Keys.ENTER);
Thread.sleep(1000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Select Year')]")));
WebElement we2 = driver.findElement(By.xpath("//div[contains(text(),'Select Year')]"));
executor.executeScript("arguments[0].click();", we2);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("vehicle-year")));
WebElement YearSelectDropdown = driver.findElement(By.id("vehicle-year"));
YearSelectDropdown.sendKeys("2011");
YearSelectDropdown.sendKeys(Keys.ENTER);
Thread.sleep(1000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Select Model')]")));
WebElement we3 = driver.findElement(By.xpath("//div[contains(text(),'Select Model')]"));
executor.executeScript("arguments[0].click();", we3);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("vehicle-model")));
WebElement VehicleSelectDropdown = driver.findElement(By.id("vehicle-model"));
VehicleSelectDropdown.sendKeys("128i Cabriolet Base Model");
VehicleSelectDropdown.sendKeys(Keys.ENTER);
It seems page require to click on dropdown first , Try this code :
wd.findElement(By.xpath("//*[#id='shopByVehicle-search-change']/div[1]/div[1]")).click();
Select SelectMakedropdown = new Select(wd.findElement(By.id("vehicle-make")));
SelectMakedropdown.selectByVisibleText("BMW");
Above will run for sure.
Related
I tried to practices selenium automation in https://www.phptravels.net/admin but i could not enter username.
private By username = By.xpath("//input[#type='text'][#name='email']");
Actions inputAct = new Actions(mngr.getDriver());
inputAct.click().sendKeys("admin#phptravels.com").perform();
mngr.getDriver().findElement(page.getUsername()).sendKeys("admin#phptravels.com");
I search the developer tools the xpath ahs unique element. Why it cannot enter the username. Thanks.
This works for me:
RemoteWebDriver driver = new FirefoxDriver();
driver.get("https://www.phptravels.net/admin");
WebElement emailInput = driver.findElement(new By.ByXPath("//input[#type='text'][#name='email']"));
emailInput.sendKeys("TEST TEST TEST");
driver.close();
you need to bypass detection methods of selenium.
ChromeOptions options = new ChromeOptions();
IWebDriver driver;
options.AddArguments("--disable-notifications");
options.AddArguments("--no-zygote");
options.AddArguments("--disable-accelerated-2d-canvas");
options.AddArguments("--disable-setuid-sandbox");
options.AddArguments("--no-first-run");
options.AddArguments("--disable-2d-canvas-clip-aa");
options.AddArgument($"--user-agent={UA}");
options.AddArguments("start-maximized");
options.AddArguments("--blink-settings=imagesEnabled=false");
options.AddUserProfilePreference("profile.default_content_setting_values.css", 2);
options.AddArguments("--disable-gpu");
options.AddArgument("ignore-certificate-errors");
options.AddExcludedArguments(new List<string>() { "enable-automation" });
options.AddArguments("--disable-blink-features=AutomationControlled");
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string title = (string)js.ExecuteScript("Object.defineProperty(navigator, 'webdriver', {get: () => false})");
driver.Navigate().GoToUrl("https://www.phptravels.net/admin");
new WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("/html/body/div[2]/form[1]/div[1]/label[1]/input"))).SendKeys("jdhfshshdf");
As described in the question, when i initialize an instance of selenium web driver, my java program does not close after the main method has finished running. I am using the sample code from the official Selenium documentation:
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", pathToWebdriver);
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
driver.get("https://google.com/ncr");
driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);
WebElement firstResult = wait.until(presenceOfElementLocated(By.cssSelector("h3>div")));
System.out.println(firstResult.getAttribute("textContent"));
} finally {
driver.quit();
}
System.out.println(Thread.getAllStackTraces().keySet());
}
Output:
[Thread[ForkJoinPool.commonPool-worker-3,5,main], Thread[Monitor Ctrl-Break,5,main], Thread[AsyncHttpClient-3-1,5,main], Thread[Signal Dispatcher,9,system], Thread[Common-Cleaner,8,InnocuousThreadGroup], Thread[process reaper,10,system], Thread[Reference Handler,10,system], Thread[AsyncHttpClient-timer-1-1,5,main], Thread[Attach Listener,9,system], Thread[AsyncHttpClient-timer-4-1,5,main], Thread[Finalizer,8,system], Thread[main,5,main]]
PS: Its the same if im using chrome webdriver or driver.close()
Edit:
This problem seems to be selenium-4.0.0-alpha only
I'm trying to create a program to automate certain downloads, however, when using Selenium-WebDriver, I find I can't seem to find the element needed to log in. I have located the correct element, however actually using the WebDriver#findElement() is giving me issues.
<input id="form-username" class="form-field" form="popup-login" type="text" name="username" value="" tabindex="1" autofocus="">
I've been trying different By methods, however none of them work, along with different ID's, albeit to no avail.
I have checked other posts, but none of them seem to fit as they are just retrieving information from specific points in the HTML like a String, where I want to input information into it.
public void start(String usernameInfo, String passwordInfo) {
driver = new HtmlUnitDriver();
driver.get("https://www.nexusmods.com");
WebElement username = driver.findElement(By.id("form-username"));
username.sendKeys(usernameInfo);
username.submit();
WebElement password = driver.findElement(By.id("form-password"));
password.sendKeys(passwordInfo);
password.submit();
System.out.println(driver.getTitle());
driver.quit();
}
The output log can be viewed here: https://hastebin.com/zuvebosaha.nginx
UPDATE:
Tried ChromeDriver, and found the following code (modified for my use)
public void start(String usernameInfo, String passwordInfo) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\veeay\\Documents\\chromedriver.exe"); //add chrome driver path (System.setProperty("webdriver.chrome.drive",chrome driver path which you downloaded)
WebDriver driver = new ChromeDriver(); // create object of ChromeDriver
driver.manage().window().maximize(); // maximize the browser window
driver.get("https://www.nexusmods.com/"); //enter url
driver.findElement(By.id("form-username")).sendKeys(usernameInfo); //type textbox's id or name or any locater along with data in sendkeys
driver.findElement(By.id("form-password")).sendKeys(passwordInfo);
driver.findElement(By.id("btnLogin")).click();
try {
Thread.sleep(2000); //used thread for hold process
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit(); //for close browser
}
resulting in the following: https://hastebin.com/iliyuvucok.cs
UPDATE 2: Oddly enough, now that I actually post the question, I'm doing good. Now I can do everything except select the sign-in button.
public void start(String usernameInfo, String passwordInfo) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\veeay\\Documents\\chromedriver.exe"); //add chrome driver path (System.setProperty("webdriver.chrome.drive",chrome driver path which you downloaded)
WebDriver driver = new ChromeDriver(); // create object of ChromeDriver
driver.manage().window().maximize(); // maximize the browser window
driver.get("https://www.nexusmods.com/Core/Libs/Common/Widgets/LoginPopUp?url=%2F%2Fwww.nexusmods.com%2F"); //enter url
driver.findElement(By.id("form-username")).sendKeys(usernameInfo); //type textbox's id or name or any locater along with data in sendkeys
driver.findElement(By.id("form-password")).sendKeys(passwordInfo);
driver.findElement(By.id("sign-in-button")).click();
try {
Thread.sleep(2000); //used thread for hold process
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit(); //for close browser
}
apparently the sign-in button is not interactable https://hastebin.com/ahuvezoxat.cs
Added explicit wait and it works:
package vee;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Vee {
#Test
public void start() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\pburgr\\Desktop\\selenium-tests\\GCH_driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// new explicit wait
WebDriverWait webDriverWait = new WebDriverWait(driver, 5);
driver.get("https://www.nexusmods.com/Core/Libs/Common/Widgets/LoginPopUp?url=%2F%2Fwww.nexusmods.com%2F");
// using explicit wait
webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("sign-in-button")));
driver.findElement(By.id("form-username")).sendKeys("some name");
driver.findElement(By.id("form-password")).sendKeys("some password");
// print true or false by the button state
System.out.println(driver.findElement(By.id("sign-in-button")).isEnabled());
driver.findElement(By.id("sign-in-button")).click();
driver.quit();
}
}
Output:
Starting ChromeDriver 74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729#{#29}) on port 4301
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1560240089.419][WARNING]: This version of ChromeDriver has not been tested with Chrome version 75.
Čer 11, 2019 10:01:31 DOP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
true
Maybe when repeating test, recaptcha pops up and disables the button.
I am getting java.lang.NullPointerException when i am trying to find elements on a webpage using #FindBy annotation.
My Code -
public class pageObject{
WebDriver driver;
#FindBy(id = "email")
WebElement searchBox;
#FindBy(id = "u_0_v")
WebElement submit;
void pageObject(String web){
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
this.driver = new FirefoxDriver(profile);
this.driver.get(web);
this.driver.manage().window().maximize();
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
searchBox.click();
searchBox.sendKeys("er");
submit.click();
}
public static void main(String[] args){
new pageObject("https://www.facebook.com/?_rdr=p");
}
}
I got an exception for the above code -
Exception -
Exception in thread "main" java.lang.NullPointerException
at com.Selenium_Practice.pageObject.<init>(pageObject.java:29)
at com.Selenium_Practice.pageObject.main(pageObject.java:35)
I also tried to use
#FindBy(how = HOW.ID , using = "email") and #FindBy(how = HOW.ID , using = "u_0_v")
but again got the same null pointer exception
You first need to init your Elements if you use Selenium's PageFactory and if you want your class to be self-containing*
pageObject(String web){
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
this.driver = new FirefoxDriver(profile);
// You need to put this line in your constructor
PageFactory.initElements(this.driver, this);
// Then follows the rest of your constructor
...
}
* meaning, that you could also init this classes elements outside the class, but I presume you want to do it inside.
When I am trying to open a site through TestNG, a security page is coming and for that I have click a link text "Continue to this website(not recommended)." that i have done through TestNG coding but it is giving java.lang.NullPointerException error.
and this is the code which i am trying......
public class Registration {
WebDriver driver;
WebElement element;
WebElement element2;
WebDriverWait waiter;
#Test(priority = 1)
public void register_With_Cash() throws RowsExceededException, BiffException, WriteException, IOException
{
File file = new File("D:\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
driver=new InternetExplorerDriver();
driver.get("https://172.25.155.250/loginpage.aspx");
sleep(10000);
waiter.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Continue to this website (not recommended).")));
driver.findElement(By.linkText("Continue to this website (not recommended).")).click();
sleep(50000);
Thanx in advance for any kind of help.
you can use the below javascript to click the Continue to the Website(not recommended) link.
driver.Navigate().GoToUrl("javascript:document.getElementById('overridelink').click()");