How to get the link using htmlunit - java

How can I simulate a click on the respective tag <a> below and grab the link contained in it?
<span class="textAlignment nextPage">
<a class="jsEnabled nextBtn cursorPointer" href="javascript:setSelectedLink('NextPageButton');" title="Next page" alt="Next page"></a>
</span>
Using htmlunit as follows to get the element but I only get null
HtmlAnchor a = page.getFirstByXPath("//a[#class='jsEnabled nextBtn cursorPointer']");

In order to simulate a click you should first fetch the element from the HtmlPage. I would use getFirstByXPath.
Then just perform the click method on the returned object.
It is unclear what you mean by first clicking in a link and then grabbing the link contained in it. If you want to, apart from clicking the anchor, getting the content of the href attribute before clicking on it then you should fetch the anchor using the same method mentioned above and before clicking on it perform the getHrefAttribute.

Related

Selenium : How to find xpath of button by LinkText?

Basically there are 3 types of Save button in a page. Now, the button which I'm trying to click on is a type="button" and remaining types of save are not defined as type="button".For all three save buttons LinkText is defined as Save. So, is there any way to click on type="button" by linkText.
HTML:
<button class="btn btn-md bgm-blue m-r-10 waves-effect" ng-click="updateUser()" type="button">Save</button>
Code which I tried:
List<WebElement> list = Util.getWebDriver().findElements(By.xpath("//*[text()='Save']"));
System.out.println("SaveButton"+list.size()); ///Returning 3 save button in a page
list.get(3).click();
Now, suppose in one page there are 4 save buttons and in another page there are 3 save buttons. So, it is not possible to make a method because each time index will differ.
If there is any way to find xpath by type="button". Will be easy for me to make a method and call it each time I want to click on"Save".
Please let me know in case of clarification.
is there any way to click on type="button" by linkText
Actually By.linkText() is use to locates <a> elements only that contain the given link text while you're trying to locate <button> element. So you can not locate desire element using By.linkText().
button which I'm trying to click on is a type="button" and remaining types of save are not defined as type="button"
As you are saying only desire button contains attribute type="button", So it is very easy to find that element using other locator as below :-
By.cssSelector() :
button[type='button']
button[type='button'][ng-click='updateUser()']
button.btn.btn-md.bgm-blue.waves-effect[type='button'][ng-click='updateUser()']
By.xpath() :
//button[text()='Save' and #type='button']
//button[.='Save' and #type='button']
//button[text()='Save' and #type='button' and #ng-click='updateUser()']
//button[.='Save' and #type='button' and #ng-click='updateUser()']
As the Save button contains class attribute you can construct an xpath as follows:
findElements(By.xpath("//button[#class='btn btn-md bgm-blue m-r-10 waves-effect'][contains(text(),'Save')]"));

how to find xpath in selenium webdriver

Following is the HTML of the page, How do i get the Xpath or is there anyother way to automate using java?In fact, we shud click on this "continue" button.
<regform-button>
<button ng-disabled="activityIndicator" ng-click="validate()" type="button">
<div template="api-loader" ng-http-loader="">
<div class="http-loader__wrapper ng-hide" ng-show="showLoader" ng-include="template">
<span class="api-loader"></span>
</div>
</div>
<ng-transclude>
</button>
</regform-button>
If you are using Google Chrome, right click on the button, and select Inspect in the popup. The html will open in a developer tools frame. Right click on the element in the developer tools frame, hover over copy, select copy xpath.
Here is the XPath to the form on the URL.
//*[#id="main-frame"]/div[1]/div[2]/div/div[1]/div[1]/form/regform-steps/ng-transclude/regform-step[1]/ng-form/ng-transclude/regform-button/button
WebDriver driver = new ChromeDriver();
driver.get("https://uk.match.com/unlogged/landing/2016/06/02/hpv-belowthefold-3steps-geo-psc-bowling?klid=6740");
//fill in fields
WebElement element = driver.findElement(By.xpath("//*[#id=\"main-frame\"]/div[1]/div[2]/div/div[1]/div[1]/form/regform-steps/ng-transclude/regform-step[1]/ng-form/ng-transclude/regform-button/button"));
element.click();
driver.findElement(By.xpath("//regform-button/button")).click();
Try opening the console for Google Chrome and typing the following:
document.evaluate("//regform-button/button", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click()
It works...that's if you've specified the required fields. Also be sure to wait for a while (2 secs to be sure) after specifying the required fields as there might be an additional load after setting the required fields.
Edit: The code is javascript..I just took the xpath given by the previous answers and used that to locate the element through js. I'm saying that "//regform-button/button" should work..
Once you have selected the required values from the drop-downs appearing before Continue button, you can click on Continue button using the following statement:
driver.findElement(By.xpath("//span[text()='Continue']")).click();
The following xpath worked for me.But I dont know, why is it different for each different browser.
For Firefox :
`driver.findElement(By.xpath("//*[#id='main-frame']/div[1]/div[2]/div/div[1]/div[1]/form/regform-steps/ng-transclude/regform-step[1]/ng-form/ng-transclude/regform-button/button")).click()`;
For chrome: driver.findElement(By.xpath("//regform-button/button")).click();

Selenium WebDriver (Java) : Handle Field Validation Message

How to handle this kind of pop-up. My goal is to get the message when Submit button clicked then validate it againts my own text (maybe using assert). I've tried to locate the element using firepath (xpath) but when i click locate Element button on firebug, the pop-up disappear.
Here is the screenshot of the pop-up.
popUp
Here is the code :
<p class="errors"></p>
<input id="email" class="form-control" type="email" value="" name="email" required="" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Email Cannot Be Empty')" placeholder="Email *" data-placeholder="X" data-format="">
Thank you in advance.
From the scrrenshot it looks like a tooltip. Something like when we mouse over Google title in https://www.google.co.in/.
To verify tooltip we can get the attribute 'title' and verify.
Example : in https://www.google.co.in/. tooltip is placed in title attribute as below.
title="Google"
<div id="hplogo" style="background-size:272px 92px;height:92px;width:272px" title="Google" onload="window.lol&&lol()" align="left">
For your scenario, the displayed tip message is available in 'oninvalid' attribute as below. So get this attribute value and validate it.
oninvalid="this.setCustomValidity('Email Cannot Be Empty')"
If the element is not inside a iframe, then you can directly try as follows:
String emailId = driver.findElement(By.id("email")).getText()
// write string equals login here comparing emailId that is captured and the one you want to compare to.
if not, first find the iframeand switch to it and then use above code to find the element. More detailed answer related to switching b/w frame is here
Finding the elements in the Pop-up:
Instead of clicking on the Locate Element button (of Firebug) first, Right click on the element you want to find in the Pop-up, and select Inspect with Firebug, which gives the corresponding HTML code for the element.
This is a bit late in the game but the way you get the custom validity message and not the generic one you have to call the reportValidity() event within JavaScript in Selenium. You'll see a driver.executeScript() method and this is where you must call the reportValidity event on the element being validated. This is how I did it:
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions
.ElementToBeClickable(By.CssSelector("input#NewPassword.form-control")));
IWebElement input = driver.FindElement(By.CssSelector("input#NewPassword.form-control"));
input.SendKeys(string.Empty);
IWebElement form = driver.FindElement(By.TagName("form"));
form.Submit();
driver.ExecuteScript("document.getElementById('NewPassword').reportValidity();");
Assert.AreEqual("New password required", input.GetAttribute("validationMessage"));

Selenium Click different ID link

How can I click on different a elements with different id attribute values in Selenium Framework?
Link ahref value are the same text.
<li>
<a id="abc_differentName_1_default_fun" href="javascript:startClient('abc_differentName_1', 'default', 'fun');">Start</a>
</li>
<li>
<a id="abc_differentName_2_default_fun" href="javascript:startClient('abc_differentName_2', 'default', 'fun');">Start</a>
</li>
<li>
<a id="xyz_differentName_xyz_default_fun" href="javascript:startClient('xyz_differentName_xyz', 'default', 'fun');">Start</a>
</li>
I don't want to create every link one click method.
My problems are I don't want to create every link one click method. I want one click method depends on the id name. Possible to create a click method example: void clickByIdName(String idName) ??
Depends on which link i clicked, it will open new windows(other page object).
Many thanks in Advance.
If there are multiple links with similar text on page, you can use id value to select each element as follows:
driver.findElement(By.cssSelector("a#abc_differentName_1_default_fun")).click();
driver.findElement(By.cssSelector("a#abc_differentName_2_default_fun")).click();
driver.findElement(By.cssSelector("a#xyz_differentName_xyz_default_fun")).click();
You don't have to use these ID attribute values to locate the link elements. There is a better way - a link text locator. You can locate all links with Start link text and choose which one you need getting it by index:
List<WebElement> links = driver.findElements(By.linkText("Start"));
links.get(0).click();
Not sure what's the exact problem here, but what is wrong with these:
driver.findElement(By.id("abc_differentName_1_default_fun")).click();
driver.findElement(By.id("abc_differentName_2_default_fun")).click();
driver.findElement(By.id("xyz_differentName_xyz_default_fun")).click();
You can use css selector to find all elements with id contain something like:
driver.findElements(By.cssSelector("[id*=_differentName_]"))
If you want void clickByIdName(String idName)
void clickByIdName(String idName) {
driver.findElement(By.Id(idName)).click();
}

findElement by class where content equals text

I'm trying to locate and click an element on my page but can't use the by.id method as the id's are generated and change per session. For most elements I can get around this by using xpath but there is a dropdown menu where this does not work. I can click the element containing the dropdown and it shows me the options. If I locate the element I need and copy it's xpath the test case won't function stating it can't find the xpath. Now next to the id the Element I'm trying to click also has a class. Problem is that this class is not unique, all menu items in the dropdown have the same class with a different text. What I would like to do is something like:
driver.findeElement(By.class("x-menu-item-text").equals("Unique text 1here").click()
The class "x-menu-item-text" is not unique but the text in this particular class is. I can't use the ID as this is automatically generated. The full code for the item or element I want to click is:
<a id="ext-comp-1035" class="x-menu-item" hidefocus="true" unselectable="on" href="#"><span id="ext-gen250" class="x-menu-item-text">Unique text 1 here</span></a>
<a id="ext-comp-1035" class="x-menu-item" hidefocus="true" unselectable="on" href="#"><span id="ext-gen250" class="x-menu-item-text">Unique text 2 here</span></a>
I'm using Selenium Webdriver with Eclipse (Java).
Allthough the answer provided seems to work on most pages and locations, there is a situation however where I can't get it to work. Can anyone advise?
There is a page with buttons and I want to click one of these buttons. If I use the following statement:
driver.findElement(By.xpath("//*[#class=' x-btn-text' and text()='Add']")).click();
I get an error message
org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
If I look at the source I see:
<button class=" x-btn-text" id="ext-gen539" type="button">Add</button>
So the element is present and visible.
I've tried adding a wait.until statement before the click statement but this does not work either:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class=' x-btn-text' and text()='Toevoegen']")));
driver.findElement(By.xpath("//*[#class=' x-btn-text' and text()='Toevoegen']")).click();
Extra information: could this problem be because I'm looking for an element that is located in a popup?
You can use xpath locator
https://newcircle.com/bookshelf/selenium_tutorial/locators
By.xpath("//span[#class='x-menu-item-text' and text()='Unique text 1here']")

Categories

Resources