How to verify links - selenium

How to verify whether links are present or not?
eg.
I have 10 links in a page, I want to verify the particular link
Is it possible?
I am using selenium with Java.
Does i can write inside the selenium code
eg
selenium.click("searchimage-size");
selenium.waitForPopUp("dataitem", "3000");
selenium.selectWindow("name=dataitem");
foreach(var link in getMyLinkTextsToTest())
{
var elementToTest = driver.findElement(By.linkText(link));
Assert.IsNotNull(elementToTest);
}

What you can do is find all links on the page like this:
var anchorTags driver.findElement(By.TagName("a"));
and then iterate through the anchorTags collection to make you you've got what you're looking for.
Or if you have a list of the link texts you can do something like this:
foreach(var link in getMyLinkTextsToTest())
{
var elementToTest = driver.findElement(By.linkText(link));
Assert.IsNotNull(elementToTest);
}
This code is all untested and right off the top of my head so you might need to do some slight modification but it should be close to usable.

if you are using Selenium 1.x you can use this code.
String xpath = "//<xpath till your anchor tag>a/#herf";
String href = selenium.getAttribute(xpath);
String expectedLink = "your link";
assertEquals(href,expectedLink);

I hope this may help you...
List<WebElement> links = driver.findElements(By.tagName("a"));
for(WebElement we : links) {
if("Specific link text".equals(we.getText("Specific link text"))) {
we.click();
}
}
I'm taking all links to List variable 'links' and iterating it. Then checking condition, for the specific text we looking in the link is presenting in the list or not. If it found out, it'll click on it

If you're looking to verify each specific for the content of href, you can use javascript to return the outerHTML for a specific Webelement which you can identify however you like; in the example below I use By.cssSelector:
WebElement Element = driver.findElement(By.cssSelector("..."));
String sourceContents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].outerHTML;", element);
assertEquals(sourceContents, "Learn More");
If you want to make it a tad more elegant you can shave the undesired elements off of the string, but this is the general case as of Selenium-java: 2.53.1 / Selenium-api: 2.47.1 as I can observe.

Best approach would be to use getText() method
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
for(WebElement specificlink : allLinks ) {
if(specificlink.getText().equals("link Text"){
//SOPL("Link found");
break;
}
}

Related

Converting SearchContext to WebElement in Selenium with Java on Chrome

Service Now has changed to using shadow root like this
<span id='s1'>
  #shadow-root
   <button>Cancel</button>
   <button>Submit</button>
</span>
I can easily get the first span:
WebElement sele = driver.findElement(By.xpath("//span[#id='s1']"));
And then get the shadow root:
SearchContext sc = sele.getShadowRoot();
But it will not let you do a
sc.findElements(By.xpath(".//button'"));
or more preferably
WebElement cancelButton = sc.findElement(By.xpath(".//button[.='Cancel']"));
You have to find with CS selector
sc.findElements(By.cssSelector(" button"));
and go through each button to get the text. To make it worse, when I try
List<WebElement> buttons = sc.findElements(By.cssSelector(" button"));
because it says there is an error with "=" and it expects "<=". No idea why. Have to do a
for (WebElement wele : sc.findElements(By.cssSelector(" button")) {
String txt = wele.getText();
if (txt.equals("Cancel")) ... // whatever you want
}
So my question is is there someway to convert "sc" to a WebElement? Even maybe someway to get itself? The equivalent of
sc.findElement(By.xpath("."));
or someway to look for xpath with SearchContext?
Looks like this discussion is exactly what you looking for.
There are several answers given there to get the Shadow Root as a WebElement object.

How to pass dynamic value into xpath in selenium, java?

I have a website, where i open contract and get the unique contractId. Then, i need to go to other page and search this id in table with pagination. I wrote code which goes to next page if this requesid(it's a link) is not found and if it exist, it just opens this requestId. But there is a problem with initialization of webelement where i'm trying add dynamic value. Selenium gives error below and i have no idea how to solve it
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[#class='link__text' and text()='222254']/../../..//input"}
(Session info: chrome=89.0.4389.72)
contractId is the variable where i store dynamic value that changes every test run. This is how the code looks like:
csecp.waitForElementVisibility(csecp.getContractStatusEmergencyChangeHeader());
int totalPages = Integer.parseInt(csecp.getTotalPagesString().getText());
for(int i = 0; i < totalPages; i++) {
csecp.sleep(500);
if (**csecp.prepareWebElementWithDynamicXpath(csecp.getContractDynamicValue(),contractId).isDisplayed()**) {
csecp.prepareWebElementWithDynamicXpath(csecp.getContractDynamicValue(),contractId).click();
csecp.waitForElementVisibility(csecp.getConfirmAMLApprovalButton());
csecp.getConfirmAMLApprovalButton().click();
break;
}
csecp.waitForElementVisibility(csecp.getNextPageButton());
csecp.getNextPageButton().click();
}
This is how i'm trying to pass dynamic valueinto xpath
private String contractDynamicValue = "//span[#class='link__text' and text()='xxxxx']/../../..//input";
public WebElement prepareWebElementWithDynamicXpath (String xpathValue, String substitutionValue ) {
return getWebDriver().findElement(By.xpath(xpathValue.replace("xxxxx", substitutionValue)));
}
You can define and use this XPath locator as following:
String contractDynamicValue = "//span[#class='link__text' and text()='%s']/../../..//input";
public WebElement prepareWebElementWithDynamicXpath (String xpathTemplate, String substitutionValue ) {
String xpath = String.format(xpathTemplate,substitutionValue);
return getWebDriver().findElement(By.xpath(xpath));
}
See the xpath that you are using is
//span[#class='link__text' and text()='xxxxx']/../../..//input
and if you wanna make xxxxx as dynamic, you could do following :-
string sub_value = "222254";
//span[#class='link__text' and text()='"+sub_value+"']/../../..//input
It's always the best solution to get element by text and the following element. For dynamic elements, you can use XPath like
//div[.='Dummy_text']/following::span[text()='test_text']
You can see some tutorials from here
https://www.guru99.com/xpath-selenium.html

selenium - how to find xpath

can any one help me for finding the correct xpath for the given link Logout
What you could do is to locate all links in your page, and then file the one corresponding to what you're searching for.
Here is the code converted to java
public static IWebElement GetLinkContainingText(string textToBeContained) {
// Here Driver is my ChromeDriver instance. You can replace a, by whatever tag your href is in.
ArrayList<WebElement> allTags = Driver.FindElements(By.Xpath("//a"));
for (WebElement v : allTags) {
if (v.GetAttribute(href).contains(textToBeContained)) {
return v;
}
}
return null;
}
calling the method would result for you in that.
WebElement elementYouSeachFor = GetLinkContainingText("http://ec2-34-210-163-161.us-west-2.compute.amazonaws.com:8094/login/index/logout");
Most likely
WebElement elementYouSeachFor = GetLinkContainingText("/logout");
would work too since there's probably not many links with logout on your page.
Hope this helps.
driver.findElement(By.xpath("//a[text()='Logout']"))
Is one way.
driver.findElement(By.linkText("Logout"));
Both could be problematic if you have more than 1 logout link on the page.
More resources on selecting elements: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/By.html

Selenium Xpath Not Matching Items

I am trying to use Selenium's Xpath ability to be able to find an set of elements. I have used FirePath on FireFox to create and test the Xpath that I have come up with and that is working just fine but when I use the Xpath in my c# test with Selenium nothing is returned.
var MiElements = this._driver.FindElements(By.XPath("//div[#class='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
and the Html looks like this:-
Can Anyone please point me right as everything that I have read the web says to me that this Xpath is correct.
Thanking you all in-advance.
Please post the actual HTML, so we can simply "drop it in" into a HTML file and try it ourselves but I noticed that there is a trailing space at the end of the class name:
<div title="Actions Selected Jobs." class="context-menu-item " .....
So force XPath to strip the trailing spaces first:
var MiElements = this._driver.FindElements(By.XPath("//div[normalize-space(#class)='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
Perhaps you don't take into consideration the time that the elements need to load and you look for them when they aren't yet "searchable". UPDATE I skipped examples regarding this issue. See Slanec's comment.
Anyway, Selenium recommends to avoid searching by xpath whenever it is possible, because of being slower and more "fragile".
You could find your element like this:
//see the method code below
WebElement div = findDivByTitle("Action Selected Jobs");
//example of searching for one (first found) element
if (div != null) {
WebElement myElement = div.findElement(By.className("context-menu-item"));
}
......
//example of searching for all the elements
if (div != null) {
WebElement myElement = div.findElements(By.className("context-menu-item-inner"));
}
//try to wrap the code above in convenient method/s with expressive names
//and separate it from test code
......
WebElement findDivByTitle(final String divTitle) {
List<WebElement> foundDivs = this._driver.findElements(By.tagName("div"));
for (WebElement div : foundDivs) {
if (element.getAttribute("title").equals(divTitle)) {
return element;
}
}
return null;
}
This is approximate code (based on your explanation), you should adapt it better to your purposes. Again, remember to take the load time into account and to separate your utility code from the test code.
Hope it helps.

How to get the full source of a link using selenium

I'm using selenium RC and want to get all the attributes and all. Something like:
link = sel.get_full_link('//a[#id="specific-link"]')
and the result would of:
print link
would be:
<a id="specific-link" name="links-name" href="url"> text </a>
Is this possible?
thanks
Here's a fancier solution:
sel.get_eval("window.document.getElementByID('ID').innerHTML")
(don't be picky with me on the javascript..)
I think the best way to do this would be to use the getHtmlSource command to get the entire HTML source, and then use either a regular expression or HTML parser to extract the element of interest.
The following Java example will output all links to System.out:
selenium.open("http://www.example.com/");
String htmlSource = selenium.getHtmlSource();
Pattern linkElementPattern = Pattern.compile("<a\\b[^>]*href=\"[^>]*>(.*?)</a>");
Matcher linkElementMatcher = linkElementPattern.matcher(htmlSource);
while (linkElementMatcher.find()) {
System.out.println(linkElementMatcher.group());
}
getAttribute
String href = selenium.getAttribute("xpath=//a[#id="specific-link"]/#href")
I've been trying to do just this, and came up with the following:-
var selenium = Selenium;
string linkText = selenium.GetText("//a[#href='/admin/design-management']");
Assert.AreEqual("Design Management", linkText);
use below code to get all the links on the page:
$str3= "window.document.getElementsByTagName('a')";
$k = $this->selenium->getEval($str3);
$url = explode(",",$k);
$array_size = count($url);
$name=array();
$l=0;
for($i=0;$i<$array_size;$i++)
{
if(!strstr($url[$i], 'javascript'))
{
$name[$l]=$url[$i];
echo "\n".$name[$l];
$l++;
}
}
If the link isn't dynamic, then try this rather cheesy, hacky solution (This is in Python):
selenium.click("//a[text()='Link Text']")<br>
selenium.wait_for_page_to_load(30000)<br>
myurl = selenium.get_location()
Cheesy but it works.
Note: this will not work if the link redirects.