sendKeys() method is not sending the keys - java

below mentioned is my code, which is not sending the keys to the textbox, however it finds the correct element as the cursor keeps blinking in the textbox.
public class cl01 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","C:\\Program Files\\Java\\geckodriver-v0.14.0-win32\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.rediff.com/");
String P1 = driver.getWindowHandle();
System.out.println(P1);
Set<String> windows = driver.getWindowHandles();
Iterator<String> W = windows.iterator();
while(W.hasNext())
{
String C1 = W.next();
System.out.println(C1);
if(!P1.equalsIgnoreCase(C1))
{
driver.switchTo().window(C1).close();
}
}
driver.switchTo().window(P1);
System.out.println("web page opened");
//Browser's position is set
driver.manage().window().setPosition(new Point(30, 40));
int height = driver.manage().window().getSize().getHeight();
System.out.println( "height of the browser is " +height);
int width = driver.manage().window().getSize().getWidth();
System.out.println("width of the browser is " +width);
driver.manage().window().maximize();
driver.findElement(By.linkText("Create a Rediffmail account")).click();
System.out.println("sign up link opened");
driver.findElement(By.xpath(".//*[#id='wrapper']/table[2]/tbody/tr[3]/td[3]/input")).sendKeys("ABC");

The code looks fine to me. Maybe it's slow to load and you need to add a wait for the first element.
I would avoid using XPath in cases like this, especially when the nested layers are so deep and you are relying on indexes. It makes for a very brittle locator. I would use a CSS selector like the below.
By.cssSelector("input[name^='name']")
I tested this and it worked for me. It's basically looking for an INPUT tag that has a name that starts with "name". The name ends with what looks like an automatically generated string but this part is unique on the page.
Here are some references to learn CSS selectors. CSS selectors are really powerful and it's time well spent to learn them.
CSS Selectors Reference
CSS Selectors Tips

Related

How can I get the position of the specified keyword in iText7?

I want to search every matched keyword in a pdf file and get their position in the page which they located.
I just found some code in iText5 which looks like match what I need
for (i = 1; i <= pageNum; i++)
{
pdfReaderContentParser.processContent(i, new RenderListener()
{
#Override
public void renderText(TextRenderInfo textRenderInfo)
{
String text = textRenderInfo.getText();
if (null != text && text.contains(KEY_WORD))
{
Float boundingRectange = textRenderInfo
.getBaseline().getBoundingRectange();
resu = new float[3];
System.out.println("======="+text);
System.out.println("h:"+boundingRectange.getHeight());
System.out.println("w:"+boundingRectange.width);
System.out.println("centerX:"+boundingRectange.getCenterX());
System.out.println("centerY:"+boundingRectange.getCenterY());
System.out.println("x:"+boundingRectange.getX());
System.out.println("y:"+boundingRectange.getY());
System.out.println("maxX:"+boundingRectange.getMaxX());
System.out.println("maxY:"+boundingRectange.getMaxY());
System.out.println("minX:"+boundingRectange.getMinX());
System.out.println("minY:"+boundingRectange.getMinY());
resu[0] = boundingRectange.x;
resu[1] = boundingRectange.y;
resu[2] = i;
}
}
#Override
public void renderImage(ImageRenderInfo arg0)
{
}
#Override
public void endTextBlock()
{
}
#Override
public void beginTextBlock()
{
}
});
But I don't know how to deal with it in iText7 .
iText7 has pdf2Data add-on which can easily help you achieving your goal (and help with other data extraction cases).
Let's say you want to extract positions of word Header. We go to https://pdf2data.online demo application, upload our template (any file containing the words you want to extract), and go to data field editor which looks like this:
Now, you can add a data field with a selector that would select the data you are interested in. In this case you can use Regular expression selector which is very flexible generally, but in our case the settings are pretty straightforward:
You can see that the editor application highlights all occurrences of the word we are searching for. Now, let's get back to the first step (there is an icon at the top right of the editor to go back to demo), and download our template (link to the bottom of the icon corresponding to the uploaded file).
Now you can look over the information on how to include pdf2Data in your project at this page: https://pdf2data.online/gettingStarted, roughly the code you need is the following:
LicenseKey.loadLicenseFile("license.xml");
Template template = Pdf2DataExtractor.parseTemplateFromPDF("Template.pdf");
Pdf2DataExtractor extractor = new Pdf2DataExtractor(template);
ParsingResult result = extractor.recognize("toParse.pdf");
for (ResultElement element : result.getResults("Headers")) {
Rectangle bbox = element.getBbox();
int page = element.getPage();
System.out.println(MessageFormat.format("Coordinates on page {0}: [{1}, {2}, {3}, {4}]",
page, bbox.getX(), bbox.getY(), bbox.getX() + bbox.getWidth(), bbox.getY() + bbox.getHeight()));
}
Example output:
Coordinates on page 1: [38.5, 788.346, 77.848, 799.446]
Coordinates on page 1: [123.05, 788.346, 162.398, 799.446]
Coordinates on page 1: [207.6, 788.346, 246.948, 799.446]
Coordinates on page 2: [38.5, 788.346, 77.848, 799.446]
Coordinates on page 2: [123.05, 788.346, 162.398, 799.446]
Coordinates on page 2: [207.6, 788.346, 246.948, 799.446]
pdf2Data add-on is closed source and available only at a commercial license option at the moment. Of course it is possible to port your code directly to iText7 and this would be another solution to the task you have, but I must warn you that your code is not universal for all scenarios, e.g. text in a PDF can be written letter by letter, instead of writing a whole word at once (the visual appearance of the two PDFs can easily stay the same), and in this case the code you attached would not work. pdf2Data handles those cases out of the box, taking the burden out of your shoulders.

Actions.dragAndDropBy is not working as expected

I wrote following piece of code to move a draggable object on
https://jqueryui.com/draggable/
driver.get("https://jqueryui.com/draggable/");
WebElement eleFrame=driver.findElement(By.className("demo-frame"));
driver.switchTo().frame(eleFrame);
WebElement ele=driver.findElement(By.xpath("//*[#id='draggable']"));
Actions move=new Actions(driver);
move.dragAndDropBy(ele, 180, 300).release().build().perform();
This code does not move the object.
when i tried
move.clickAndHold(ele).moveByOffset(300, 100).release().build().perform();
it is working fine.I read the documnets it is saying dragAndropBy have internally same functionality as clickAndHold and then moving by some offset.
I have tested it before for both vertical/horizontal slider and it used to work fine.
Please suggest what is the problem with dragAndDropBy code. or some other functionality is actually expected out of it.
Any help will be much appreciated.
Actually it's pretty weird that move.clickAndHold(ele).moveByOffset(300, 100).release().build().perform(); is working for you... I've tried them both and they throw the same exception:
org.openqa.selenium.UnsupportedCommandException: moveto did not match a known command
However, there are open bugs in Selelnium and in geckodriver on this issue.
BTW, the only difference between the two is that you don't have the ButtonReleaseAction in your custom action.
You can use dragAndDrop() method.
Actions action = new Actions(driver);
action.dragAndDrop(sourceElement, destinationElement).build().perform();
Refere tutorial http://www.seleniumeasy.com/selenium-tutorials/drag-and-drop-using-webdriver-action-class
No need to release() When "dragAndDropBy" is used.
Try this:
move.dragAndDropBy(ele, 180, 300).build().perform();
Multiple Controls Drag and Drop to the Same Destination.
WebElement element_1 = driver.findElement(By.xpath("//li[#data-lobid='12']")); //source element 1
WebElement element_2 = driver.findElement(By.xpath("//li[#data-lobid='21']")); //source element 2
WebElement destination = driver.findElement(By.xpath(".//*[#id='lobModalPopUp']/div")); //destination path
int[] array_source = new int[]{12,21}; // create fixed array for id number of source element 1 and 2
for(int i = 0; i<array_source.length; i++) //Passing id number of source element 1 and 2 inside the for loop.
{
WebElement all_source_element = driver.findElement(By.xpath("//li[#data-lobid='"+arraylobs[i]+"']")); // getting all source element with the help of fixed array.
Actions drag = new Actions(driver);
drag.clickAndHold(all_source_element).build().perform();
Thread.sleep(3500);
drag.clickAndHold().moveToElement(destination).release(destination).build().perform();
Thread.sleep(3500);
}
driver.get("https://jqueryui.com/draggable/");
driver.switchTo().frame(0);
WebElement dragMe = driver.findElement(By.cssSelector(".ui-draggable-handle"));
new Actions(driver).dragAndDropBy(dragMe, dragMe.getLocation().getX()+100, dragMe.getLocation().getY()+100).perform();
This is how to use the dragAndDropBy(WebElement source, int xOffset, int yOffset) method provided in Actions class to perform drag and drop operations.
WebElement source: web-element that you want to drag around.
int xOffset and int yOffset are future x-axis and y-axis coordinate positions. Basically, the code gets the current x-axis and y-axis coordinate positions and adds int number to move the draggable element.
Please make sure to set up your driver properly before using this block of code.

How to get an active window title between two browser tabs/windows using Selenium Java

I can switch between two tabs/windows but my requirement is to know or get active window between them.
In my project, on a click of a webElement of a page a random pop(tab/window) gets opened and I would like to know whether that(new) window has focus or my original page.
I tried to use JNA Api to get the active window and its title but my web page is
remotely located.
Perfect solution is greatly appreciated.
Thanks
driver.getTitle() will give you the title of the page that you can use to determine which page you are on or if you are on the page where you want to be and then use the logic to switch window if required. getTitle() returns a String and you can use one of the string methods to compare the title, for example:
String title = getDriver().getTitle();
if(!title.equals("Expected Title")) {
//may be you would like to switch window here
}
String title = driver.getTitle()
This will give you the title of the page which you can refer to using Selenium to figure out which page the driver is currently on.
I wrote my own method to switch to a window if the window title is known, maybe some of this would be helpful. I used Selenide (Java) methods for this, but if you've got Vanilla WebDriver, you can achieve the same thing
/** Switches user to window of user's choice */
public static void switchToWindow(String windowTitle) {
WebDriver driver = getWebDriver();
// Get list of all open tabs - note behaviour may be different between FireFox and Chrome.
ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
// iterate through open tabs. If the title of the page is contained in the tab, switch to it.
for (String windowHandle : driver.getWindowHandles()) {
String title = getWebDriver().getTitle();
driver.switchTo().window(windowHandle);
if (title.equalsIgnoreCase(windowTitle)) {
break;
}
}
}
This method might not be lightening fast, but it will iterate through current open windows and check the title matches the one you've specified.
If you want to assert the title, you could use the xpath selector:
String pageTitle = driver.findElement(By.xpath("//title[text() = 'Title you looking for']"));
This is a dumb example with you can surround with try/catch, implement assertions or other technique to have the result you need.
In JavaScript, for me this worked. After clicking on the first link of bing search results in edge, my link opened in a new tab. I explicitly mentioned to stay in the same tab.
async function switchTab() {
await driver.getAllWindowHandles().then(async function (handles) {
await driver.switchTo().window(handles[1]);
});
}
//get initial window handles
Set<String> prevWindowHandles = driver.getWindowHandles();
while(true){
//get current window handles
Set<String> currWindowHandles = driver.getWindowHandles();
//if one of the current window handles not equals to
//any of the previous window handles,switch to this window
//and prevWindowHandles = currWindowHandles
for(String prevHandle : prevWindowHandles){
int noEqualNum = 0;
for(String currHandle : currWindowHandles){
if(!currHandle.equals(prevHandle))
noEqualNum++
}
if(noEqualNum == currWindowHandles.size()){
driver.switchTo().window(currWindow);
prevWindowHandles = currWindowHandles;
break;
}
}
}

selenium firefox modal displays as a pop-up window, not a modal

I'm trying to use Selenium to test out a form on a website that consists of multiple pages. There are modals that are suppose to appear on some of the pages based on options that are selected. Currently I'm having trouble getting Selenium to work properly with Fireforx and the modals. Chrome acts as expected, and I haven't bothered with I.E. yet.
When I work through the pages manually with Firefox, everything works as expected.
When I run my Selenium script the modal displays like a Windows pop-up window, not a modal.
I'm using driver.switchTo().alert().accept(); to handle the modals, and the first modal I encounter will close, but once I get to the next page the Selenium code is unable to find any of the elements on the page.
Here is the code I use to click a button:
public void pushButton(String[] values) {
System.out.println("\t Click (" + values[1] + ")");
setLocator(values[0], values[1]);
try {
clickWhenReady(locator).click();
} catch (Exception e) {
System.out.println("Could not find id or xpath value: " + values[1]);
e.printStackTrace();
}
}
private void setLocator(String byType, String value) {
if(byType.toUpperCase().equals("ID")) {
locator= By.id(value);
} else if(byType.toUpperCase().equals("XPATH")){
locator= By.xpath(value);
}
}
private WebElement whenReady(By locator){
WebElement element = (new WebDriverWait(driver, 30))
.until(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private WebElement clickWhenReady(By locator){
WebElement element = (new WebDriverWait(driver, 30))
.until(ExpectedConditions.elementToBeClickable(locator));
return element;
}
First of all, modals are not alerts so, driver.switchTo().alert().accept(); will probably not going to buy you anything.
The real issue could be the modals take longer to fade out and blocking Selenium to interact with the page. Your best bet will be to try waiting for the modal to completely disappear from the dom and then try interacting with the elements. For that you can use invisibilityOfElementLocated of ExpectedConditions or similar mechanism. See this

Need help on find the textbox in the newly opened window in selenium webdriver

String parentHandle = driver.getWindowHandle();
driver.findElement(By.id("ImageButton5")).click();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
driver.findElement(By.id("txtEnterDescription")).sendKeys("Test");
driver.findElement(By.id("chklstAllprocedure_0")).click();
I used this code and I got the error as
"Exception in thread "main"
org.openqa.selenium.NoSuchElementException: Unable to find element
with id == txtEnterDescription (WARNING: The server did not provide
any stacktrace information) Command duration or timeout: 30.05
seconds". The HTML code for this text box is ""
Please help me out of this
you may face "NoSuchElementException" only in two case for sure.
1.The Element is yet to be Loaded
- Have an appropriate wait logic here.
2. You may try to locate the element wrongly .
- Double Check your Xpath/ID(what ever)
- Make sure you are in the same frame where the element is present.If not, switch to the frame then.
Just make sure you are switching to the right window
Reason 1 : Just make sure you are switching to the right window
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows
Resaon 2 : wait for the element
WebdriverWait wait = new WebdriverWait(driver,7000);
wait.until(ExpectedConditions.visbilityOfElementLocatedBy(By.name("nameofElement")));
Reason 3 : check if the element is in a frame if yes switch to the frame before
driver.switchTo.frame("frameName");
Let know if it works ..
Guess the problem is in your switch to logic. I think when you are switching it is passing the code of the parent instead of the child. For this scenario create two local variables parent and child. Loop through the window handles using an iterator and set the parent and child window id's to the variables and pass the child id to the switchTo method. This should work. Keep me posted. Happy coding.

Categories