Java Selenium, how to get linkText (anchor) from link WebElement - java

I have a WebElement containing link found by url. I can extract url by:
element.getAttribute("href");
But the question is: how to extract it's anchor, I'm trying like this:
webElement.getAttribute("linkText");
It gives me null value. I'm 100% sure this link has an anchor. Is there any way to get anchor ? It's more complicated, but example simplified code could look like this:
WebDriver driver = new FirefoxDriver();
driver.get("http://stackoverflow.com/questions/tagged/java");
WebElement link = driver.findElement(By.linkText("Bicycles"));
System.out.println(link.getAttribute("href")); // shows http://bicycles.stackexchange.com/
System.out.println(link.getAttribute("linkText")); // shows null

Try this:
System.out.println(link.getText());

If getText() returns an empty String, try the innerHTML attribute:
String text = element.getAttribute("innerHTML")

By "Anchor" I think you mean the text of the link? If so, then you can use .getText() since an <a> is a block level element.
link.getText();

Here you can store your id text:
String text = driver.findElement(By.id("Text")).getText();
System.out.println(text);

Related

Use Selenium Java to get string text from HTML

I want to get Selenium with Chromedriver to recognize and import a line of html text into a Webelement variable.
Given this HTML:
<li id="password_rules">
<strong>Password Rules</strong>
<p>The database password rules conform with...:</p>
<ul>
<li>The password can not be the same as the user id.</li>
<li>Password length must be between 8 and 25 characters.</li>
</ul>
</li>
I want to grab the text in the last list element ("Password length must be between 8 and 25 characters.").
This is the java code I'm attempting to use:
WebElement passwordCriteria = driver.findElement(By.xpath("//*[#id = 'password_rules']//*[contains(text(), 'Password length must be between ')]"));
String lineText = passwordCriteria.getText();
When that Java executes, it returns an error saying the element cannot be found:
Exception in thread "main"
org.openqa.selenium.InvalidSelectorException: invalid selector: Unable
to locate an element with the xpath expression //[contains((text(),
'Password length must be between ')] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string
'//[contains((text(), 'Password length must be between ')]' is not a
valid XPath expression.
Any insight is much appreciated.
If you are grabbing a WebElement by it's id, then you don't need your extra specific xPath. id is supposed to be unique by convention. If you have other html elements with the same id, consider changing them to a class.
You should be able to grab the element like this:
WebElement passwordCriteria = driver.findElement(By.id("password_rules"));
If you're committed to finding the element by the id containing some text then the way you should do it is as follows:
WebElement passwordCriteria = driver.findElement(By.xpath("//*[contains((text(),'Password length must be between')]"));
Also, sometimes Selenium will complain if elements are not visible on the page when you try and reference them. Sometimes you need to wait, other times you need to perform some other action to make the text visible before referencing it, like hovering the mouse over a dropdown, etc.
For example
Suppose the html you pasted here is an error message. This error message does not start out as being 'visible', but instead it is shown after the user types their password in incorrectly. In such an instance, Selenium won't let you reference the text from an element inside this div, since it's not currently view-able. Instead, what you would have to do is use Selenium to input the incorrect password in the fields, wait for the error message to be displayed, and then finally reference the WebElement, only after it is able to be seen.
EDIT:
I misread OP's intention. The element that OP is trying to reference is NOT the element with the id, but rather a child of that element. Instead of rewriting my answer, I will point out that #Grasshopper answer has both css and xPath solutions.
You can try these locators if the concerned li is always the last child.
Css - "li[id='password_rules'] > ul > li:last-child"
xpath - "//li[#id='password_rules']/ul/li[last()]"
As per your question as the desired text is within Password Rules you have to induce WebDriverWait with ExpectedConditions as textToBePresentInElementLocated and then retrieve the text as follows :
new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//li[#id='password_rules']//ul//li"), "Password length"));
String lineText = driver.findElement(By.xpath("//li[#id='password_rules']//ul//li[contains(.,'Password length')]")).getAttribute("innerHTML");
Thank you for the help everyone. I finally got it using the following:
new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//li[#id = 'password_rules']"), "Password length must be between "));
WebElement passwordCriteria = driver.findElement(By.xpath("//li[#id = 'password_rules']/ul/li[2]);
String lineText = passwordCriteria.getText();
Your original example had // which should only be used at the beginning of an xpath.

How can I get text from element with Selenium webdriver and Java?

My code:
WebDriver driver = new SafariDriver();
driver.get("http://bet.hkjc.com/football/default.aspx");
WebElement matchs = driver.findElement(By.cssSelector("span.Head to Head"));
System.out.println(matchs);
driver.quit();
How can I crawl Manchester Utd and Celta Vigo?
WebElement matchs = driver.findElement(By.xpath("//a[#title='Head to Head']"));
System.out.println(matchs.getText());
Use firebug and firepath addons in firefox and inspect that element and get the xpath and put it here inside double quotes in this code :
System.out.println(driver.findElement(By.xpath("")).getText());
If you don't know how to use firebug and firepath refer this link
You can locate the element either by css selector or xpath selector
By using xpath
driver.findElement(By.xpath("//a[#title='Head to Head']"));
By using css Selector
driver.findElement(By.cssSelector("span > a[title='Head to Head']"));
OR Try somethings like this if not getting the match
driver.findElement(By.cssSelector("td.cteams.ttgR2>span>a[title='Head to Head']"));
Note : in your code you are trying like span.Head to Head in CSS selector . dot represents the class and according to your path you are locating span tag which have class name "Head to Head" which doesn't exist in your dom as this is the title of anchor tag.
Went through the Firebug and Firepath plugins of Firefox initially to get the Xpath or css path
Explore some blogs to get clear understanding, you will be able to create by yourself
Refer This link for the same
I assume all the above answers doesn't work for you and am providing another answer.
I can see both the texts are under "a" tag. So the idea is to navigate to the element and use getText() - which returns the visible text.
String word = driver.findElement(By.xpath("//span/a")).getText();
System.out.println(word);
Hope this works for you.
In all of my tests I'm using the getAttribute like this to get text and it is working fine for me on all drivers :
assertEquals(strCity, txtCity.getAttribute("value"));

How to use getText and get an attribute in Selenium WebDriver

Below are separate textboxt1 IDs for getting the text:
WebElement Text = driver.findElement(By.id("incident.number"));
String result = Text.getText();
How can I write the code for getting the values from gettext?
Below are textbox2 id:
driver.findElement(By.id("38240a5edb5912000c91d540cf9619b9_text"));
I want to get the value from textbox1 to textbox2. How can I get the attributes from getText?
You can get the the value of text box using getAttribute("value") like driver.findElement(By.id("38240a5edb5912000c91d540cf9619b9_text")).getAttribute("value"). This will return you the value of a textbox.
You can get the string in the textbox by getAttribute("value"):
String textboxValue = driver.findElement(By.id("38240a5edb5912000c91d540cf9619b9_text")).getAttribute("value");
If you are able to get the value from the textbox, then just pass that string to textbox2 using sendKeys as below.
driver.findElement(By.id("38240a5edb5912000c91d540cf9619b9_text")).sendKeys(result);
I am supposing that the locator is fine and able to locate the elements.

how to get a text string from

I am creating an automatic test for some webs and I'm using WebDriver, TestNG and code that is written in Java. On the page is shown register of categories, in parentheses is number of auctions and i need to get this number as variable, but i don't know, how.
I use the following code:
WebElement number1_1_vse = (driver.findElement(By.linkText("Vše")));
String text_vse1_1 = number1_1_vse.getText();
but output is only: "Vše" without (number of auctions)
link to the website
screenshot -> image with the number
can anyone advise me please?
With linktext you are finding the nested a which text is Vše only. You need to find the li containing the text Vše (949)
Use the following css selector to identify the element
By bycss =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse = driver.findElement(bycss );
String text_vse1_1 = number1_1_vse.getText();
WebElement parent = number1_1_vse.findElement(By.xpath(".."));
// which will give you access to <li>
List<WebElement> childs = parent.findElements(By.xpath(".//*"));
// childs.get(1) has the result.
Please try to get the xpath value and then try to search it with below mentioned syntax :
findelementbyxpath("//*[#id="post-form"]/h2")
To get xpath value of and element : right click --> inspect element --> right click copy xpath

webdriver classname with space using java

This question received great answers in jquery and I was wondering if someone could give an example of this in Java please?
I'm doing driver.findElement(By.className("current time")).click(); The space is the issue, and I see the explanation at the link, but I'm not sure how to handle it in java, and don't have access to change the class name.
Pasting example of what i get in the firefox inspect id: Example with cssSelector below did not work, but i may be missing something.
<span>
<a class="current time" href="http://someurl/" onclick="s_objectID="http://someur/">url</a>
</span>
Instead of class name you can use a css selector. You don't mention the tagname for the class 'current time'. I am assuming it to be input, so your css selector work be,
WebElement element = driver.findElement(By.cssSelector("input[class='current time']"));
element.click();
Edit#1 Based on html provided,
Looking at the html in your comment, it seems you have quite a few options to find the webElement. Here are your options,
WebElement element = driver.findElement(By.cssSelector("a[class='current time']"));
element.click();
or this should work too,
WebElement element = driver.findElement(By.cssSelector("a.current.time"));
element.click();
You can also use linkText since the element is link. From the html you provided, the link text is 'url'
WebElement element = driver.findElement(By.linkText("url"));
element.click();
You can also use By.partialLinkText("partial link text here");
You can also use xpath as:
WebElement element = driver.findElement(By.xpath("//a[#class='current time']"));
element.click();
OR,
WebElement element = driver.findElement(By.xpath("//a[text() = 'url']"));
element.click();
For a less fragile test, another option is to use an XPATH which doesn't depend of the order of classes, like:
WebElement element = driver.findElement(By.xpath("//a[contains(#class, 'current') and contains(#class, 'time')]"));
Whenever you found some space in the class name you need to switch to cssSelector Locator.
Convert a class name to cssSelector if it is having a space as below.
In your case it would be:
WebElement element = driver.findElement(By.cssSelector(".current.time"));
element.click();
PS: add . [dot] in start of class name and replace the space with . [dot] to convert class name to cssSelector.

Categories

Resources