Selenium Webdriver to handle java script text box - java

I am trying to specify zip code to a input field to fetch the restaurant locations. I am able to specify the zip code and unable to hit the enter key. As its doesn't has enter button it needs to be handled via javascript. Need help in resolving issue:
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
String baseURL = "http://www.thecheesecakefactory.com/";
driver.get(baseURL);
// Go to Menu
driver.findElement(By.xpath("//*[#id='topNav']/li[1]/a")).click();
// Click on Pizza
driver.findElement(By.xpath("//*[#id='firstScroller']/li[7]/a")).click();
// Select Hawallian Pizza
driver.findElement(By.xpath("//*[#id='secondScroller']/li[6]/a")).click();
//String pageTitle = "Hawaiian Pizza";
String aTitle = driver.getTitle();
if (aTitle.equalsIgnoreCase("Hawaiian Pizza")){
System.out.println("Yes its Hawaiian Pizza");
System.out.println(driver.getTitle());
}
//Click to order and get locations
driver.findElement(By.xpath("//*[#id='receiptMenu']/div[1]/div[3]/div/a/b")).click();
WebElement element;
element = driver.findElement(By.xpath("//*[#id='location_box']/div[2]/input"));
element.sendKeys("84604", Keys.ENTER);
}

WebElement element;
element = driver.findElement("//*[#id='location_box']/div[2]/input");
element.sendKeys("84604", Keys.ENTER);
There is an typo error in the above code.
WebElement element;
element = driver.findElement(By.xpath("//*[#id='location_box']/div[2]/input"));
element.sendKeys("84604", Keys.ENTER);
I checked the code it is working fine.

Related

Selenium Chrome Driver Trouble Selecting or Inputting for Login

I am trying to setup a tool to monitor my Plex account. I am using Chrome Driver to try and login to my Plex account with an email and password. I cannot manage to locate the input fields no matter what I try, whether by ID, XPath etc. I have run a test with the Selenium Chrome Plugin and it manages to to find the element by ID but when running the following Java code I cannot get the driver to find the email and password fields. The extra code is to deal with the Cookies pop up and seems to work, at least it dismisses the pop up.
...
File file = new File("src/chromedriver88.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
LOGGER.info("Got Chrome driver - " + file.exists());
ChromeOptions options = new ChromeOptions();
options.addArguments("no-sandbox");
driver.get("https://www.plex.tv/en-gb/sign-in/");
// Sort out the cookies pop up if it's there
boolean present;
try {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/a[2]"));
present = true;
} catch (NoSuchElementException e) {
present = false;
}
if (present) {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/a[2]")).click();
}
// Wait for log in button to exist
WebDriverWait wait = new WebDriverWait(driver, 30);
#SuppressWarnings("unused")
WebElement elementLogin = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("email")));
// Send log in details
WebElement username = driver.findElement(By.id("email"));
username.sendKeys("...");
WebElement pwd = driver.findElement(By.id("password"));
pwd.sendKeys("...");
// Click log in
driver.findElement(By.xpath("//html/body/div[1]/div/div/div/div[1]/form/button")).click();
Your email and password input inside a frame:
<iframe src="..." id="fedauth-iFrame"
#document
You need switch it first, use .frameToBeAvailableAndSwitchToIt:
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("fedauth-iFrame")));
WebElement username = wait.until(ExpectedConditions.elementToBeClickable(By.id("email")));
username.sendKeys("email");
WebElement pwd = wait.until(ExpectedConditions.elementToBeClickable(By.id("password")));
pwd.sendKeys("password");

how to select the auto popup hotel names in a hotel booking site in Selenium

I am working on automating the following hotel booking site. I need to select the auto popup hotel name once I type the hotel in the first search box...I don't know how to do this.
I have navigated through the link and clicked Demo, then clicked the first link that appeared on the page.
I tried to click on the first search box and I need to enter a hotel from the auto popup list...I don't know how to do this because this has no PAC-item...
https://www.phptravels.net/home
public class Question1 {
WebDriver Driver = null;
WebDriverWait wait = null;
String url = "https://phptravels.com/demo/";
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver","src\\test\\resources\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
options.addArguments("--disable-popup-blocking");
Driver = new ChromeDriver(options);
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
wait = new WebDriverWait(Driver, 25);
String winHandle = Driver.getWindowHandle();
//Driver.switchTo().window(winHandle);
//new WebDriverWait(Driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='webpush-onsite']")));
//new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#deny.button.close"))).click();
}
#Test
public void f() {
Driver.get(url);
System.out.println("*****In the main page*****");
String xpathDemo = "//*[#id=\"mega-nav-navigation\"]/div/ul[1]/li[2]/a";
Driver.findElement(By.xpath(xpathDemo)).click();
String Title = "PHPTRAVELS | Travel Technology Partner";
/*try {
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")));
Driver.findElement(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")).click();
} catch(Exception e) {
System.out.println("No popup..."+ e.getMessage());
}
*/
String username = Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[3]/div[2]/div")).getAttribute("innerText");
username = username.substring(6) ;
String password = username.substring(30);
System.out.println("Username text :"+username + "\npassword is:"+password);
Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/a")).click();
utils.HelperFunctions2.switchToWindow(Driver, Title);
Driver.findElement(By.xpath("//*[#id=\"s2id_autogen16\"]")).click();
Driver.findElement(By.xpath("/html/body/div[7]/ul")).click();
}
#AfterTest
public void afterTest() {
Driver.quit();
}
}
Below xpath is result of 1st hotel, changing the index it will intreact with rest of the elements.
After filing text to the hotel text box.
give Thread.sleep(2000);
use below xpath. I hope it will work
(.//ul[#class='select2-results']/following::div[#class='select2-result-label'])[2]
I have already built bots, auto image pickers and more and I have never used the By.xpath method. Classname is much easier to use!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
Driver.findElement(By.className(getInputFocusId).click();
//now focused!
String text = Driver.findElement(By.className("select2-match").getText();
//text is the first default search match of the list.
}
There is also a more complicated way.
In Selenium you can sendKeys to an Element.
If the input element is focused the first match is also focused.
By clicking on Enter the focused match will be searched and displayed in the input element.
Finally you have to read the data from the input Element!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
WebElement element = Driver.findElement(By.className(getInputFocusId);
element.click();
//element.sendKeys(Key.DOWN);
element.sendKeys(Key.ENTER);
String text = element.getText();
//this is the text of the first search match
//if you want to get the second or third just repeat sending the DOWN key.
}
IMPORTANT: Make sure to run each line delayed (200ms is a good time). This helps you finding errors... For example in the Instagram Auth Process I delayed a lot of lines, and it finally worked!
I hope my answer helps you!!!

unable to click on Webelement on web Page

I'm trying to click on web element and enter text inside it.
Steps:
Launch "https://www.phptravels.net/"
Click on tours tab.
Perform send keys operation on search field.
1.I tried using click on search box and entering text via send keys but unable to do so, After that I performed click action and send keys using javaScript but this is also not working.
I have written different xpath for the same but no positive results.
//code is as below
public class HandlingDropDown2 {
static WebElement element;
static WebDriver driver;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "Driver/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.phptravels.net/");
element = driver.findElement(By.xpath("//span[contains(text(),'Tours ')]"));
element.click();
Thread.sleep(2000);
element = driver.findElement(By.xpath("//button[contains(text(),'Got it!')]"));
element.click();
Thread.sleep(2000);
element = driver.findElement(By.xpath("//div[#id='s2id_autogen5']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
System.out.println("clicked on autogen box");
//element.click();
Thread.sleep(2000);
element = driver.findElement(By.xpath("//div[#class='select2-drop select2-display-none select2-with-searchbox select2-drop-active']"));
JavascriptExecutor executor2 = (JavascriptExecutor)driver;
executor2.executeScript("arguments[0].'value='Test';",element);
//element.sendKeys("test");
}
}
Expected Result: User must be able to enter some text via automation.
Actual Result: Unable to perform click and sendkeys using JavaScript and simple selenium methods.
Remember the functionality of sendKeys
Fir of all, your xPath is div element and you are trying to do sendKeys in div element which is wrong. If you observed there is span element named 'Search by Listing or City Name'. If you click there then your input element gets visible where you can click() and sendKeys("")
Try,
// click on below span element to get input visibled,
element = driver.findElement(By.xpath("//span[text()='Search by Listing or City Name']"));
element.click();
Then your input element is now available where you can click and sendkeys
element = driver.findElement(By.xpath("//div[#id='select2-drop']//input[#class='select2-input'][last()]"));
element.click();
element.sendKeys("test");

Selenium and Java: How do I get all of the text after a WebElement

I am coding a program in Java using WebDriver and am having a little bit of trouble getting the text after the select webElement.
The HTML code for the part of the website that I want is as follows:
<select name="language" id="langSelect" style="width:100px;">
<option value="1" >Français</option>
</select>
</div>
<div id="content">
<div id="Pagination"></div>
<div id="mid">
</div>
</div>
The textbox class codes for a search bar and a drop down bar of languages
My Java code is currently able to open chrome using the chrome driver and is able to type into the search bar. I am however not able to get the text that results from the entry.
Image
In the image here, I entered "avoir" into the search bar, and I want all of the text inside the boxes after which do not seem to have any id's or names to be used inside the xpath.
Can someone please help me in finding how to get and save the text from those fields after the dropdown language menu?
Thank you in advance!
The code I have so far:
//import statements not shown
public class WebScraper {
public WebScraper() {
}
public WebDriver driver = new ChromeDriver();
public void openTestSite() {
driver.navigate().to(the URL for the website);
}
public void enter(String word) {
WebElement query_editbox =
driver.findElement(By.id("query"));
query_editbox.sendKeys(word);
query_editbox.sendKeys(Keys.RETURN);
}
public void getText() {
//List<WebElement> searchResults =
driver.findElements(By.xpath("//div[#id='mid']/div"));
// Writer writer = new BufferedWriter(new
OutputStreamWriter(new FileOutputStream("status.txt"),
"utf-8"));
//int[] index = {0};
WebElement result=driver.findElement(By.id("mid"));
System.out.println(result.getText());
}
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "chromedriver");
System.out.println("Hello");
WebScraper webSrcaper = new WebScraper();
webSrcapper.openTestSite();
webSrcapper.enter("avoir");
webSrcapper.getText();
System.out.println("Hello");
}
}
I have specified three approaches to extract the text from the result box. Please check all the approaches and use the required approach.
If you want to extract all the text, then you can find the element of the result box and then you can get the Text from that.
WebElement result=driver.findElement(By.id("mid"));
System.out.println(result.getText());
If you want to extract the Text based on the Section by section, then you can go with the below approach,
List<WebElement> sectionList=driver.findElements(By.xpath("//div[#id='mid']/div"));
int i=0;
for(WebElement element:sectionList){
System.out.println("Section "+i+":"+element.getText());
i++;
}
If you want to extract the text from specific section, then you can do with the below approach
List<WebElement> sectionList=driver.findElements(By.xpath("//div[#id='mid']/div"));
int i=0;
//Inorder to get the Section 3 Content
int section=2;
for(WebElement element:sectionList){
if(section==i){
System.out.println("Section "+i+":"+element.getText());
}
i++;
}
Edit: To address followup question
I would suggest to use some explicit wait after doing some action which resulting in some element rendering. In your code, after doing some modification, I am getting the result as expected.
In openTestSite method, I have just added the explicit wait to ensure the page load after loading the URL
In enter method, actually you are getting the autocomplete suggestion after entering the query value .So, we need to just select the value from the autocomplete.
In getText method, Search result is taking more time.So, we need to add some explicit wait using any one of the dynamically loading element locator.
Code:
openTestSite Method:
public void openTestSite() {
//driver.navigate().to(the URL for the website);
driver.get("https://wonef.fr/try/");
driver.manage().window().maximize();
//Explicit wait is added after the Page load
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("WoNeF"));
}
enter Method:
public void enter(String word) {
WebElement query_editbox =
driver.findElement(By.id("query"));
query_editbox.sendKeys(word);
//AutoComplete is happening even after sending the Enter Key.
// So, Value needs to be selected from the autocomplete
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='autocomplete']/div")));
List<WebElement> matchedList=driver.findElements(By.xpath("//div[#class='autocomplete']/div"));
System.out.println(matchedList.size());
for(WebElement element : matchedList){
if(element.getText().equalsIgnoreCase(word)){
element.click();
}
}
//query_editbox.sendKeys(Keys.RETURN);
}
getText Method:
public void getText() {
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='mid']/div")));
WebElement result=driver.findElement(By.id("mid"));
System.out.println(result.getText());
}
I have tested with the above modified code and it is working fine.
In order to inspect the relevant results for your query, common strategy would be to load a list of search results:
List<WebElement> searchResults = driver.findElements(By.xpath("//div[#id='mid']/div"));
Now you can use stream to iterate over the list and extract your relevant text, by getting the text from child elements of each result:
int[] index = {0};
searchResults.stream().forEach(result -> {
System.out.println("Printing query result of index: " + index[0]);
result.findElements(By.xpath(".//*")).stream().forEach(webElement -> {
try {
System.out.println(webElement.getText());
} catch (Exception e) {
// Do nothing
}
});
index[0]++;
});
And you would get the output:

PhantomJSDriver: Not able to switch to newly opened browser window

I have been trying to use PhantomJSWebDriver framework for automating an application using Headless browser. The main issue is as we can successfully switch between windows in firefox or IE windows, here I am not able to switch between windows based on handles. Please help me.
Below is the code I have tried so far.
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
driver = new PhantomJSDriver();
driver.get(application url);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
WebElement txtUsername = driver.findElement(By.id("it_C_C5"));
txtUsername.sendKeys("sreenis");
WebElement txtPassword = driver.findElement(By.id("it_C_C7"));
txtPassword.sendKeys("sreeni");
WebElement btnLogin = driver.findElement(By.id("ic_C_C8"));
btnLogin.click();
Thread.sleep(10000);
String winTitle = "Role profile selection";
boolean bool = switchWindow(winTitle);
if (bool){
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
else {
System.out.println("Switch to window '" + winTitle + "' failed!");
driver.quit();
}
public static boolean switchWindow(String windowtitle){
String mainWindowsHandle = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
System.out.println(handles.size());
for(String winHandle : handles){
driver.switchTo().window(winHandle);
System.out.println(driver.getTitle());
if(driver.getTitle().toLowerCase().equals(windowtitle)){
return true;
}
}
driver.switchTo().window(mainWindowsHandle);
return false;
}
When I tried to print the window titles in collection, it is only printing the parent window and not the other windows. I am not able to guess what is happening since nothing can be seen and it is headless testing. Please suggest me is there any other way so that I can test the app with many browser windows.
Actions act = new Actions(d);
act.contextClick(elements).sendKeys("W").perform();
Set<String> win = d.getWindowHandles();
Iterator <String> itrwin = win.iterator();
String parent = itrwin.next();
String child = itrwin.next();
d.switchTo().window(child);
identify an web element first using findElement() and store it in element.

Categories

Resources