How do I get a value from href?
like this eg:
<div id="cont"><div class="bclass1" id="idOne">Test</div>
<div id="testId"><a href="**NEED THIS VALUE AS STRING**">
<img src="img1.png" class="clasOne" />
</a>
</div>
</div>
</div>
I need that value as string.
I've tried with this:
String e = driverCE.findElement(By.xpath("//div[#id='testId']")).getAttribute("href");
JOptionPane.showMessageDialog(null, e);
But just returns NULL value...
You have pointed your element to 'div' instead of 'a'
Try the below code
driverCE.findElement(By.xpath("//div[#id='testId']/a")).getAttribute("href");
If you got more than one anchor tag, the following code snippet will help to find all the links pointed by href
//find all anchor tags in the page
List<WebElement> refList = driver.findElements(By.tagName("a"));
//iterate over web elements and use the getAttribute method to
//find the hypertext reference's value.
for(WebElement we : refList) {
System.out.println(we.getAttribute("href"));
}
Related
Hello I am using HtmlUnit library and I need to get some href attribute from an a tag, inside some div:
<div class="threadpostedin td alt">
<p>Forum:<br>
<a href="programming/website-development/"
title="Website Development">Website
Development</a></p>
</div>
This div is located inside a <li> which is located inside a <ol>
to get the ol I did this:
HtmlOrderedList l = (HtmlOrderedList) this.page.getElementById("searchbits");
The html:
<ol class="searchbits" id="searchbits" start="1">
Now from the div I posted, I need to get the href "programming/website-development/", but I am not sure how to do this. Yes the div has a class name, but if I do
for (DomElement ele : l.getChildElements()) {
System.out.println(ele.getByXPath("//div[#class='threadpostedin td alt']").size());
break;
}
it will print 15, because overall there are 15 lists in the ol, in each list there is one div with class threadpostedin td alt. What I need to do, is the the exact div with class threadpostedin td alt in the DomElement I got from the iteration, and not get the list of all divs with that class.
Is there a way to do this with HtmlUnit?
I assume you have more links than one to make it more detailed.
HtmlElement element = page.getByXPath("//div[#class='threadpostedin td alt']").get(0);
DomNodeList<DomNode> nodes = element.querySelectorAll("a");
for(DomNode a : nodes) {
if(a.getAttributes().getNamedItem("href") !=null) {
String href = page.getFullyQualifiedUrl(a.getAttributes().getNamedItem("href").getNodeValue()).toString().toLowerCase();
String baseUrl = page.getBaseURL().toString();
}
}
due to the fact i'm using selenium for the first time i have a questin on selecting a child element without parameters.
I'm trying to get the child-div "element to be clicked" to perform a click.
Java:
WebElement element = driver.findElement(By.className("parent"));
WebElement element2 = element.findElement(By.xpath("/div/div/div")); // should be wrong
element2.click();
Given HTML-Code:
<div class="parent">
<div>
<div>
<div>element to be clicked</div>
</div>
</div>
</div>
You can use
element.findElement(By.xpath("//div[text()='element to be clicked']"));
With RegEx
element.findElement(By.xpath("//div[matches(text(),'RegExExpression']"));
While there's nothing to identify directly, we can do something like this..
List<WebElement> divs = driver.findElements(By.tagname("div")); //This will return all div elements
Then we can try something unique to that div..
for(int i = 0; i < divs.size(); i++) {
if(divs.get(i).getText().equals("element to be clicked")) {
divs.get(i).click();
break;
}
}
I have been trying to get the anchor link via WebDriver but somehow, things aren't working as desired and I am not getting the element.
Below is the HTML Structure:
<div id="1">
<table width="100%">
<tr>
<td>.....</td>
<td>
<ul class="bullet">
<li>....</li>
<li>....</li>
<li>
myText
</li> // myText is the text I am searching for
</ul>
</td>
</tr>
</table>
<div>....</div>
</div>
The <li> elements contains anchor tags with links only. No id or any other attribute they contain. The only difference is the text displayed by them and hence, I am passing myText to detect exactly what I need.
And for this, the java code I have been trying is:
driver.get("url");
Thread.sleep() //waiting for elements to get loaded. Exceptional Handling not done.
WebElement divOne = driver.findElement(By.id("1"));
WebElement ul = divOne.findElement(By.className("bullet"));
WebElement anchor = null;
try{
anchor = ul.findElement(By.partialLinkText("myText"));
}catch(NoSuchElementException ex){
LOGGER.warn("Not able to locate tag:" + linkText + "\n");
}
String myLink = anchor.getAttribute("href"); // null pointer exception
I don't understand why is this happening. What is the correct way to do this? Should I use some other method?
driver.findElement(By.xpath("//a[contains(text(),'myTest')]"));
that searches for myTest text. I haven't tried the code, I hope it helps you
you can use any of the below. Should work for you
List<WebElement> anchor = driver.findElements(By.partialLinkText("myText"));
or
driver.findElements(By.linkText("myText"))
or
driver.findElements(By.Xpath("//a[contains(text(),'myText')]"));
String myLink = anchor.getAttribute("href"); // null pointer exception
You are getting exception because you didn't set the anchor value, anchor variable is created and intialized to null and after that it is never updated.
I think the correct code should be below
String myLink = element.getAttribute("href");
Try using a WebDriver instance directly instead of WebElement instance...i.e., use driver instead of ul..
you can try with wait,
element = new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.linkText("myText")));
In a list of 8 Elements I would select the one that contains the search text in children div. I need this because the elements of the list changes order every time. Here I would like to select the one that contains the text "TITLE TO LISTEN". How do I scroll through the list and select the wish li?
Thanks in advance
Here one li:
...
<li id="3636863298979137009" class="clearfix" data-size="1" data-fixed="1" data-side="r">
<div class="userContentWrapper">
<div class="jki">
<span class="userContent">
TITLE TO LISTEN
</div>
<div class="TimelineUFI uiContainer">
<form id="u_0_b0" class="able_item collapsed_s autoexpand_mode" onsubmit="return window.Event && E" action="/ajax/ufi/modify.php" method="post" >
<input type="hidden" value="1" name="data_only_response" autocomplete="off">
<div class="TimelineFeedbackHeader">
<a class="ction_link" role="button" title="Journal" data-ft="{"tn":"J","type":25}" rel="dialog" href="/ajax/" tabindex="0" rip-style-bordercolor-backup="" style="" rip-style-borderstyle-backup="" >LISTEN</a>
</div>
</form>
</div>
</div>
</li>
</ol>
</div>
...
I tried this code, but it don't work because the elements ids change each time.
driver.findElement(By.xpath("//li[8]/div[2]/div/div[2]/form/div/div/span[2]/a")).click();
For example:
If text contain "TEXT TO LISTEN": li[3]/div[2]/div/div/div[2]/div/div/span
Link "listen" i want to click : li[3]/div[2]/div/div[2]/form/div/div/span[2]/a
here is number 3, but the order may change. I would first like to get that number and then click on the right link
Use this
driver.findElement(By.xpath("//li[contains(text(), 'Your text goes here')]"))
EDIT: just realised it's very old ques and you might have got ans by now, so for others who are looking for answer to this question.
You could get list of all li elements, and then search for specified text
for(int i=0; i< listOfLiElements.Count, i++){
if(listOfLiElements[i].FindElement(By.ClassName("userContent")).Text == "TITLE TO LISTEN")
{
correctElement = listOfLiElements[i].FindElement(By.TagName("a"));
i =listOfLiElements.Count;
}
}
Well, then just iterate through for each and ask if the current element has the right text inside it.
List<Element> listOfLiTags = driver.findElement(By.Id("yourUlId")).findElements(By.TagName("li"));
for(Element li : listOfLiTags) {
String text = li.getElement(By.ClassName("userContent").getText();
if(text.equals("TITLE TO LISTEN") {
//do whatever you want and don't forget break
break;
}
}
Note that this is much more easier with CssSelector API.
List<Element> listOfSpans = driver.findElements(
By.CssSelector("ul[id=yourId] li span[class=userContent]");
Now just iterate and ask for the right text:)
You can try this :
public void ClickLink()
{
WebElement ol =driver.findElement(By.id("ol"));
List<WebElement> lis=ol.findElements(By.tagName("li"));
ArrayList<String> listFromGUI=new ArrayList<>();
for(int i=0;i<lis.size();i++)
{
WebElement li=ol.findElement(By.xpath("//ol[#id='ol']/li["+(i+1)+"]/div[2]/div/div/div[2]/div/div/span"));
if(li.getText().trim().equals("TEXT TO LISTEN"))
{
WebElement link=ol.findElement(By.xpath("//ol[#id='ol']/li["+(i+1)+"]/div[2]/div/div[2]/form/div/div/span[2]/a"));
if(link.getText().trim().equals("LISTEN"))
{
link.click();
break;
}
}
}
}
I've got the following HTML code:
<div class="ui-selectmenu-menu" style="z-index: 1; top: 251px; left: 37px;">
<ul class="ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom" aria-hidden="true" role="listbox" aria-labelledby="gwt-uid-191-button" id="gwt-uid-191-menu" style="width: 270px; height: auto;" aria-disabled="false" aria-activedescendant="ui-selectmenu-item-999">
<li role="presentation" class="ui-selectmenu-item-selected">
All Applications</li>
<li role="presentation" class="">
Option Alpha</li>
<li role="presentation" class="ui-corner-bottom">
Option Beta</li>
</ul>
</div>
...
<div class="ui-selectmenu-menu"...>...</div>
I'm able to get the WebElement for ui-selectmenu-menu like this (there are many on the page; hence, the use of findElements) :
List<WebElement> dropdowns = driver.findElements(By.className("ui-selectmenu-menu"));
And the ul below it like this:
WebElement ddChild = dropdowns.get(0).findElement(By.className("ui-selectmenu-menu-dropdown"));
I'm even able to grab all the li under the ddChild like this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li[*]"));
But the problem that I can't seem to figure out how to grab the text-value of the <a href="#nogo"... tag under each li element.
I'd like to be able to loop through all the ddOpts and grab the <a href="#nogo"... text values and save them to an ArrayList<String>.
So, for example, my first ArrayList<String> value would contain All Applications, then Option Alpha, then Option Beta, and then jump to the next ul element from the next dropdowns and do the whole process again, all while adding to the ArrayList<String>.
I'm sure its a simple solution but I've got limited experience with Selenium WebDriver.
Thanks!
PS: Is there a simple way to grab the child of a WebElement?
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
links.add(we.getText();
}
To extract the href attribute of the WebElement (referring to the anchor tag <a> in this example, do this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
// ADD all the href attribute strings to the list
links.add(we.getAttribute("href"));
}
This may also solve your problem:
List<WebElement> dropdowns = driver.findElements(By.className("x-combo-list"));
WebElement ddChild = dropdowns.get(0).findElement(By.className("x-combo-list-inner"));
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id=\"x-auto-98\"]/div[4]"));
for(WebElement we:ddOpts){
System.out.println(we.getText());
if(we.getText().contains("ROLE_MANAGER")){
we.sendKeys("ROLE_MANAGER");
we.click();
break;
}
}
the below code will select the OptionAlpha in the dropdown of the above HTML code
driver.findElement(By.xpath("//*[#class='ui-selectmenu-menu')).click();
driver.findElement(By.xpath("//*[#class='ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom']//**[text()='Option Alpha']")).click();
Please try the below code to get all the links in the <a href
List<WebElement> allLis = driver.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a");
// Looping through above list using for-each loop
for(WebElement eachLi : allLis) {
System.out.println(eachLi.getText());
}
Hope this helps.
href="#nogo" is same for all the anchor tags, so it might create ambiguity in selecting the item by the method
dropdowns.findelement(By.linktext("#nogo"));