selenium web driver sendKeys in a loop java - java

How should I use sendKeys in loop? First time sendKeys work correct, but second time, on the new page - exception.
public class main {
public static void main(String args[]) throws Exception{
System.setProperty("webdriver.gecko.driver", "C:\\Users\\asdasd\\Desktop\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.kommersant.ru");
Scanner scanner = new Scanner(System.in);
while(true) {
WebElement search = driver.findElement(By.cssSelector(".search__input"));
// WebElement searchButton = driver.findElement(By.cssSelector(".search__button"));
String s = scanner.nextLine();
if(s.equals("exit")){
break;
}
else {
WebDriverWait wait = new WebDriverWait(driver, 10);
search.sendKeys(s);
WebElement searchButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".search__button")));
searchButton.click();
searchButton.click();
}
}
driver.quit();
}
}

Try to get your loop condition right.The problem lies there.

Related

How to use explicit wait condition with selenium 4.0

using Java 17 and slenium 4.0
wait.until(ExpectedConditions.titleContains("BrowserStack"));
here is full code :
public class mainTestClass {
public static final String USERNAME = "myuser *****";
public static final String AUTOMATE_KEY = "my ke *****";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
public static void main(String[] args) throws Exception {
Thread object1 = new Thread(new TestClass1());
object1.start();
Thread object2 = new Thread(new TestClass2());
object2.start();
Thread object3 = new Thread(new TestClass3());
object3.start();
}
public void executeTest(Hashtable<String, String> capsHashtable) {
String key;
DesiredCapabilities caps = new DesiredCapabilities();
// Iterate over the hashtable and set the capabilities
Set<String> keys = capsHashtable.keySet();
Iterator<String> itr = keys.iterator();
while (itr.hasNext()) {
key = itr.next();
caps.setCapability(key, capsHashtable.get(key));
}
WebDriver driver;
try {
driver = new RemoteWebDriver(new URL(URL), caps);
JavascriptExecutor jse = (JavascriptExecutor)driver;
// Searching for 'BrowserStack' on google.com
driver.get("https://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
// Setting the status of test as 'passed' or 'failed' based on the condition; if title of the web page contains 'BrowserStack'
WebDriverWait wait = new WebDriverWait(driver, 5);
try {
// wait.until(ExpectedConditions.titleContains("BrowserStack"));
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Title matched!\"}}");
}
catch(Exception e) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Title not matched\"}}");
}
System.out.println(driver.getTitle());
driver.quit();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
This is cause in Selenium 4.0.0 (Stable)
WebDriverWait which takes driver and timeoutInSeconds long, have been Deprecated
#Deprecated
public WebDriverWait(WebDriver driver, long timeoutInSeconds) {
this(driver, Duration.ofSeconds(timeoutInSeconds));
}
Fix:
Selenium devs have given this method instead
public WebDriverWait(WebDriver driver, Duration timeout) {
this(
driver,
timeout,
Duration.ofMillis(DEFAULT_SLEEP_TIMEOUT),
Clock.systemDefaultZone(),
Sleeper.SYSTEM_SLEEPER);
}
so your effective code will be :
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
wait.until(ExpectedConditions.titleContains("BrowserStack"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
}
catch(Exception e) {
e.printStackTrace();
}

Selenium button submit /click is not redirecting to success page from chrome web driver

I am facing issues with Selenium when navigating from one page to another.
Below is the code. If I click on following element a jQuery image will open until the next page gets loaded. But it's not navigating to next page itself. The image keeps on rotating and window will close that. Why?
I am getting a NoSuchElementFoundException
Chrome Version : 58.0.3029.110
driver.findElement(By.name("continue")).click();
#Test
public void executeLoginApp() throws InterruptedException {
driver.navigate()
.to("url with login application");
WebElement userName = driver.findElement(By.id("uname"));
WebElement pwd = driver.findElement(By.id("passwd"));
userName.sendKeys("test");
pwd.sendKeys("test");
Thread.sleep(2000);
javaScriptExecutor.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Thread.sleep(2000);
//driver.findElement(By.xpath("//input[#name='continue']")).click();
//Thread.sleep(1000);
//driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.findElement(By.name("continue")).click();
//signOn.click();
callYourInformation();
}
private void callYourInformation() {
/*try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String previousURL = driver.getCurrentUrl();
ExpectedCondition e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return (d.getCurrentUrl() != previousURL);
}};
wait.until(e);}*/
// currentURL = driver.getCurrentUrl();
if (driver.getCurrentUrl().contains("yourinfo")) {
// testing yourinfo page
WebElement emailAddress = driver.findElement(By.id("emailAddress"));
emailAddress.clear();
emailAddress.sendKeys("selenium#wwwmail.com");
WebElement addressLine1 = driver.findElement(By.id("addressLine1"));
addressLine1.clear();
addressLine1.sendKeys("New york");
WebElement grossAnnualIncome = driver.findElement(By.id("grossAnnualIncome"));
grossAnnualIncome.sendKeys(String.valueOf(6000));
WebElement submit = driver.findElement(By.id("submitApplication"));
submit.click();
driver.findElement(By.id("Continue")).click();
}
else{
do other logic.
}
I tried all the ways but no luck. Commented lines are my tries but none of them redirects to that page.

Not able to get links of all the total pages

I'm trying to type selenium in google and get all the title text of result in a notepad file. i want to get all available links on all the pages, till last page of search. but only 1st page's link i am getting. when i debug and run, it is working for some 10 pages.help me in this.
JAVA code:
public class weblink
{
public static void main(String[] args) throws IOException, InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "E:\\disha.shah/myWork/eclipse/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
PrintStream ps = new PrintStream(new File(("E:\\disha1.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//*[#id='rso']//h3/a"));
for (WebElement webElement : findElements)
{
System.out.println("-" + webElement.getText()); // for title
//System.out.println(webElement.getAttribute("href")); // for links
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
System.setOut(ps);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
Thread.sleep(1000);
if(driver.findElement(By.linkText("Next")).isDisplayed()== true)
{
driver.findElement(By.linkText("Next")).click();
}
else
{
System.out.println("All Link is Covered");
}
}
while(driver.findElement(By.linkText("Next")).isDisplayed() );
{
//Thread.sleep(2000);
}
}
}
I've done some correction. the updated code is below.-
public static void main(String[] args) throws IOException, InterruptedException
{
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "D:/Application/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
Boolean nextButtonFlag = true;
// Create two separate file storing the result
PrintStream searchTitle = new PrintStream(new File(("D:\\Titles.txt")));
PrintStream searchLink = new PrintStream(new File(("D:\\Links.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for (WebElement element : findElements)
{
// Write all received links and title inn txt file
searchTitle.append(element.getText()+"\n");
searchLink.append(element.getAttribute("href")+"\n");
}
Thread.sleep(2000);
try
{
driver.findElement(By.linkText("Next")).click();
}
catch(Exception e)
{
// no more next button to navigate further link
nextButtonFlag=false;
}
Thread.sleep(2500);
}
while(nextButtonFlag);
System.out.println("Execution done");
searchTitle.close();
searchLink.close();
}
}

How can I choose browser and then choose my specific URL from user

I'm new to Automation testing using Selenium. That's why, I'm facing issue regarding to taking browser and the URL from user input . Like, when my code is executed, first user input is choosen as your organisation and second is choosen as your URL like Google,Facebook etc.
public class Pages {
private enum Organization {
Firefox, Chrom
}
static Organization obj;
private static Pages Chrom;
private static Scanner reader;
private static Scanner reader_1;
public static void main(String[]args) throws InterruptedException {
char ch;
String org;
do
{
System.out.println("");
reader = new Scanner(System.in);
System.out.println("Please Enter The Browser Name :");
org = reader.nextLine();
obj=Organization.valueOf(org);
switch(obj)
{
case Firefox:
Pages.Firefoxdriver();
break;
case Chrom:
Pages.Chromedriver();
break;
default:
System.out.println("You Have Selected Wrong Browser ");
}
reader_1 = new Scanner(System.in);
System.out.println("Please a key followed by ENTER: \n ");
ch = reader_1.next().charAt(0);
} while (ch != 'q');
}
public static void Firefoxdriver(){
WebDriver driver = new FirefoxDriver();
driver.get("http://qa-0.ls.vu");
}
public static void Chromedriver(){
System.setProperty("webdriver.chrome.driver","E:\\workspace\\chromeDriver\\chromeDriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.get("http://qa-0.ls.vu");
}
public void IEdriver(){
File file =new File("C:/Users/mkv/workspace/ServerDrivers/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driverIE=new InternetExplorerDriver();
driverIE.navigate().to("http://www.msn.com");
}
}
I fixed a few issues and reorganized the code. This is a non-typical way to use Selenium. Most scripts don't ask the user what browser they want to use, etc. You are also going to have an issue if they misspell the browser name. I'm hoping (?) that you are just doing this for fun to try out Selenium.
Some of the things that I fixed:
You can reuse reader.
Removed some extra variables, etc.
Separated the conversion of the user input to a driver into a function, getDriver(), and it returns a WebDriver instance that you can reuse.
Added IE to the enum and getDriver().
Fixed some typos and spelling mistakes.
public class Pages
{
private static WebDriver driver;
private static Scanner reader;
public static void main(String[] args) throws InterruptedException
{
char ch;
do
{
System.out.println();
reader = new Scanner(System.in);
System.out.print("Please enter the browser name: ");
driver = getDriver(reader.nextLine());
driver.get("http://qa-0.ls.vu");
System.out.print("Press q to quit followed by ENTER: ");
reader = new Scanner(System.in);
ch = reader.next().charAt(0);
} while (ch != 'q');
}
public static WebDriver getDriver(String browserName)
{
WebDriver driver = null;
Browsers browser = Browsers.valueOf(browserName.toUpperCase());
switch (browser)
{
case FIREFOX:
System.out.println("Launching Firefox");
driver = new FirefoxDriver();
break;
case CHROME:
System.out.println("Launching Chrome");
System.setProperty("webdriver.chrome.driver", "E:\\workspace\\chromeDriver\\chromeDriver.exe");
driver = new ChromeDriver();
break;
case IE:
System.out.println("Launching IE");
System.setProperty("webdriver.ie.driver", "C:/Users/mkv/workspace/ServerDrivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
break;
default:
System.out.println("You have selected a browser that isn't available.");
}
return driver;
}
private enum Browsers
{
FIREFOX, CHROME, IE
}
}

Unable to switch between frames in WebDriver

I am working on contacts creation page in www.salesforce.com developer login account. Anybody can create a free developer login account and access this page.
I am unable to switch between frames in Lookup window. There are two frames, one is search frame with textbox and button to search and below that is results frame for displaying search results with hyperlinks for selection. I am specifying the frames by frame name or id, but webDriver switches to search frame and does the searching but then is not able to locate the results frame with NoSuchFrameException.
If I do not switch to search frame initially but directly switch to results frame, it is indeed successful in the locating the results frame which displays results of some recent searches done by default.
How do I switch from search frame to results frame ? Given below is my code
public class Acc_Parent
{
WebDriver driver;
FileInputStream fis;
XSSFWorkbook wb;
XSSFSheet sh;
#Test
public void createParent() throws IOException, InterruptedException, FileNotFoundException
{
driver = new FirefoxDriver();
//System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
//driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://test.salesforce.com");
fis = new FileInputStream("C:/Users/psit/Documents/Login.xlsx");
wb = new XSSFWorkbook(fis);
sh = wb.getSheetAt(0);
driver.findElement(By.xpath(".//*[#id='username']")).sendKeys(sh.getRow(1).getCell(0).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='password']")).sendKeys(sh.getRow(1).getCell(1).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='Login']")).click();
fis = new FileInputStream("C:/Users/psit/Documents/Input.xlsx");
wb = new XSSFWorkbook(fis);
sh = wb.getSheet("Parent");
driver.findElement(By.xpath(".//*[#id='Account_Tab']/a")).click();
driver.findElement(By.xpath(".//*[#id='hotlist']/table/tbody/tr/td[2]/input")).click();
driver.findElement(By.xpath(".//*[#id='j_id0:acctFrm:nmsrch']")).sendKeys(sh.getRow(1).getCell(1).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='j_id0:acctFrm']/div[1]/div[2]/table/tbody/tr/td[2]/input")).click();
try
{
driver.findElement(By.linkText("click here")).click();
driver.findElement(By.xpath(".//*[#id='parentAcc']")).sendKeys(sh.getRow(1).getCell(1).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='childAcc']")).sendKeys(sh.getRow(1).getCell(2).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:0:actFields']")).sendKeys(sh.getRow(1).getCell(3).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:2:actFields']")).sendKeys(sh.getRow(1).getCell(4).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:4:actFields']")).sendKeys(sh.getRow(1).getCell(5).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:6:actFields']")).sendKeys(sh.getRow(1).getCell(6).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:8:actFields']")).sendKeys(Integer.toString((int)sh.getRow(1).getCell(7).getNumericCellValue()));
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:1:actFields']")).sendKeys(sh.getRow(1).getCell(8).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:3:actFields']")).sendKeys(sh.getRow(1).getCell(9).getStringCellValue());
String mainWindow = driver.getWindowHandle();
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:5:actFields_lkwgt']/img")).click();
Thread.sleep(5000);
Set<String> winhand = driver.getWindowHandles();
for(String str : winhand)
{
if(!str.equalsIgnoreCase(mainWindow))
{
driver.switchTo().window(str);
break;
}
}
try
{
driver.switchTo().frame("searchFrame");
driver.findElement(By.xpath(".//*[#id='lksrch']")).sendKeys(sh.getRow(1).getCell(10).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='theForm']/div/div[2]/input[2]")).click();
Thread.sleep(5000);
driver.switchTo().frame("resultsFrame");
driver.findElement(By.linkText(sh.getRow(1).getCell(10).getStringCellValue())).click();
driver.switchTo().window(mainWindow);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:7:actFields_lkwgt']/img")).click();
Thread.sleep(5000);
Set<String> winhandle = driver.getWindowHandles();
for(String str : winhandle)
{
if(!str.equalsIgnoreCase(mainWindow))
{
driver.switchTo().window(str);
break;
}
}
try
{
driver.switchTo().frame("searchFrame");
driver.findElement(By.xpath(".//*[#id='lksrch']")).sendKeys(sh.getRow(1).getCell(11).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='theForm']/div/div[2]/input[2]")).click();
Thread.sleep(5000);
driver.switchTo().frame("resultsFrame");
driver.findElement(By.linkText(sh.getRow(1).getCell(11).getStringCellValue())).click();
driver.switchTo().window(mainWindow);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println();
driver.close();
driver.switchTo().window(mainWindow);
System.out.println("State/Region not Found");
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println();
driver.close();
driver.switchTo().window(mainWindow);
}
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:j_id34:save']")).click();
Before switching to resultsFrame try to switch to defaultContent or your main frame and then switch to resultsFrame. The thing is webdriver searches the frame in current context. So under searchFrame it will never find the resultsFrame (As both might be under main frame).
Hope this helps.

Categories