Webdriver Xpath - what is difference between By.Name and By.Xpath? - java

I`m trying to use xpath type of parameter in my webdriver script.
However, although this parameter actually selects the same HTML tag:
By START_BUTTON = By.xpath(".//*[#name='MyName']");
as this one
By START_BUTTON = By.name("MyName");
I`m not being able to use the by.xpath in my testing script while the by.name is working fine
Not sure why I`m facing this issue. When tested in Firebug/FirePath the path:
.//*[#name='MyName'] - points exactly to the same A tag as By.name("MyName");
Thanks

My bad, I had the part of the code commented which actually caused this.
Sorry for bothering you.
Regards

Posting it for reference :
These are the locator strategies which helps to identify an element.
Following strategies are mainly used to identify an element :
By ID
By Name
By Class Name
By Tag Name
By Link Text
By Partial Link Text
By CSS
By XPath

Related

cant find the element using classname in selenium java

I'am using selenium framework to test my own website. Im trying to click on specific icon which using anchor tag. I have java selenium code to click but couldn't click. Tried many xpath, css selectors, class name and names. but didn't worked. But can run the script and it is opening the chrome and navigating to entered domain but the clicking option is not working
above code I need to click nav-twitter class anchor option . which will create another tab in chrome to show my twitter page. but after running the app .it is only navigating to the page domain and nothing works.
So, This is my code where I have added. until the maximize everything works but not the anchor tag
This kind of error im getting when running the script in chrome. Please anyone let me know where I have been wrong here or is there are any way to make it happen. Thanks in advance.
Whenever you are initiating webdriver make sure to add implicit wait statement, so it can wait for sometime before looking for objects. Add below statement right after chromedriver initialization and your code should work without any issues.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Your locator is slightly off. In your code you are looking for an element with tagName as twitter which doesn't exists. Instead you can use either of the following locator strategies:
Using cssSelector:
WebElement navTwitter = driver.findElement(By.cssSelector("a.nav-twitter[name='twitter']"));
navTwitter.click();
Using xpath:
WebElement navTwitter = driver.findElement(By.xpath("//a[#class='nav-twitter' and name='twitter']"));
navTwitter.click();
You have used wrong selector/locator here. "twitter" is not tag name, Tag name is the value from less than symbol to the first space or greater than symbol. Words like div, p, a, span are the tag names.
So here a is the tag name and name, class, href are attribute which you can use while forming xpath or css locators. So you can create multiple locators here:
By using class name attribute
By.className("nav-twitter");
By creating xpath using name attribute
By.xpath("//a[#name='twitter']");]
By creating xpath using class attribute
By.xpath("//a[#class='nav-twitter']");
By creating css locator using class attribute.
By.cssSelector("a[class*='nav-twitter']");
By using dot symbol in css selector with class name
By.cssSelector("a.nav-twitter");
Similarly you can create css selector with name too. Since there are multiple tags, so you can not use a tag directly and If you want to use By.tagName("a") then it will click on first tag present on the page
Note: We use dot with class name and Hash (#) with Id name while forming css selectors.

How to locate dynamic downloaded filename using Selenium + Java

I am not able to locate the chrome downloaded filename using locator. I need to get the filename to proceed further on automation to verify the content.
Element HTML:
<a is="action-link" id="file-link" focus-row-control="" focus-type="fileLink" tabindex="0" role="link" href="https://energyfuture.cgi.com/pasdemo/operations/QueryDisplay!displayQuery.action?QUERY_TIMESTAMP=1614571607262" class="">Facility Balance_1614571607828.xlsx</a>
Here the numbers of filename are dynamic, but the prefix Facility Balance will be constant.
code I have tried:
driver.navigate().to("chrome://downloads/");
String Text = driver.findElement(By.xpath("//*[#id='file-link']")).getText();
OR
String AttributeData = driver.findElement(By.xpath("//*[contains(text(),'Facility Balance')]")).getAttribute("linkText");
For starters
.getAttribute("linkText");
will not work because your target node does not contain an attribute called linkText.
The second point,
By.xpath("//*[#id='file-link']")
might not work if you have multiple elements with the same ID on the page (this include popups). Consider refining your xpath to be more explicit. For example, By.xpath("//a[#id='file-link' and ...]") where the ... are additional conditions that will refine your search to find only one.
Out of curiosity, did you try your Xpath directly in the browser developer's tools? Before you attempt to code things like this, you should always attempt to evaluate your XPath expressions to make sure that 1) they are accurate and 2) they are not ambiguous. Unfortunately, given the amount of information posted, this is the extent of the help I can give you.

How to get value from <h1> tag using class in Selenium WebDriver, Java

I have html code:
<div class="formCaptionContainer fill-width" data-dyn-bind="sizing: { width: $dyn.layout.Size.available }">
<h1 class="formCaption" data-dyn-bind="text: $data.Caption, click: $data.GoGridView">Expense report for Aditi Mehta - GS1-000282, testing2</h1>
<h2 class="formCaption-context" data-dyn-bind="text: $data.ParentTitleFields">Aditi Mehta : GS1-000282</h2>
</div>
I want to get the value Expense report for Aditi Mehta - GS1-000282, testing2 from /h1 tag
Any one know how to do it?
I've tried :
By.xpath(".//div[#class='formCaption']/h1";
Above showing no element found
By.className("formCaption");
Above showing blank data
By.xpath(".//*[#class='formCaption']/h1");
Above showing no element found
This code work for me very well
String textprint=driver.findElement(By.xpath("//h2[#class='formCaption-context']")).getText();
System.out.println(textprint);
Hope It will solve your problem
Try this one
String msg= driver.findElement(By.xpath(//div[contains(#class='formCaptionContainer')]/h1 ).getText();
Can you try the below Xpath.
String msg=driver.findElement(By.xpath("//div[#class='formCaptionContainer fill-width']/h1[#class='formCaption-context']")).getText();
As per the HTML you have shared, the node attributes looks dynamic to me. So we have to induce WebDriverWait as follows :
new WebDriverWait(driver, 10).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//h1[#class='formCaption']"), "Aditi Mehta - GS1-"));
System.out.println(driver.findElement(By.xpath("//h1[#class='formCaption']")).getAttribute("innerHTML"));
You need to consider your locator strategy, the following provide good preferences for general case approach.
location by ID globally unique elements
locate by name for page unique elements
locate by css as catch all case
You should also take a look at the PageObject pattern.
It appears the page is using a JS library to display the contents through late binding/resolution. Your test needs allow for this and wait until the page elements you are interested in are fully rendered. Find out from the developers what the element looks like before it is resolved and afterwards. Late resolution is one considerations in determining your locator strategy. The strategy should include fluent waiting and default time-outs for elements to appear.
This is not a problem of fixing a single locator.
Thanks all for your help. It is working fine now. I use the below code
By headingExpenseText = By.xpath("//*[#class='formCaption'][contains(text(),'Expense report for')]");
public String getTitleEx()
{
return driver.findElement(headingExpenseText).getAttribute("innerHTML");
}
This worked for me:
String titleElem = driver.findElement(By.xpath("//*[#class='formCaptionContainer fill-width']/h1")).getAttribute("innerHTML");
assertEquals("Worked", titleElem);
What do you need exactly, Data displayed on web page or textValue used in HTML code?
If your locator is correct , then instead of getText(), you can try getAttibute("innerHTML") like below,
By.xpath("//*[#class='formCaption'][contains(text(),'Aditi Mehta')]").getAttribute("innerHTML");

Selenium 3 upgrade issue with class name

I have upgraded my selenium framework to selenium 3.4 version and I am getting the below errors:
If the Class Name has a space then FindElement fails to return list of ReadOnlyCollection<IWebElement>
What steps will reproduce the problem?
1.Not working:
FindElements(By.ClassName("CLASS NAME"));
2. Working:
FindElements(By.ClassName("CLASSNAME"));
Now most of xpath contains class name with spaces and my scripts`are not working.
To make all xpaths in my script without spaces is a huge task. It will take more time to maintain this.
Can anyone suggest me or do you have any work-around to make a minimal change and script will be fine?
Also will the selenium team fix this issue?
The thing is that there is no spaces allowed in a classname
If you are seeing classname like :
<input class="class name"/>
then it represents 2 classes first is class and second is name
Now come to selenium :
By.className() selector doesn't allows you to use compound classes. like By.className("class name")
If you want to manipulate compound class the you have to use xpath in this way
driver.findElement(By.xpath("//span[#class='class name']")
OR CSS Selector in this way
driver.findElement(By.cssSelector(".class.name")

HtmlUnit accessing an element without id or Name

How can I access this element:
<input type="submit" value="Save as XML" onclick="some code goes here">
More info: I have to access programmatically a web page and simulate clicking on a button on it, which then will generate a xml file which I hope to be able to save on the local machine.
I am trying to do so by using HtmlUnit libraries, but all examples I could find use getElementById() or getElementByName() methods. Unfortunately, this exact element doesn't have a name or Id, so I failed miserably. I supposed then that the thing I have to do is use the getByXPath() method but I got completely lost into XPath documentation(this matter is all new to me).
I have been stuck on this for a couple of hours so I really need all the help I can get.
Thanks in advance.
There are several options for an XPATH to select that input element.
Below is one option, which looks throughout the document for an input element that has an attribute named type with the value "submit" and an attribute named value with the value "Save as XML".
//input[#type='submit' and #value='Save as XML']
If you could provide a little bit more structure, a more specific (and efficient) XPATH could be created. For instance, something like this might work:
/html/body//form//input[#type='submit' and #value='Save as XML']
You should be able to use the XPATH with code like this:
client = new WebClient(BrowserVersion.FIREFOX_3)
client.javaScriptEnabled = false
page = client.getPage(url)
submitButton = page.getByXPath("/html/body//form//input[#type='submit' and #value='Save as XML']")
Although I would, in most cases, recommend using XPath, if you don't know anything about it you can try the getInputByValue(String value) method. This is an example based on your question:
// Fetch the form somehow
HtmlForm form = this.page.getForms().get(0);
// Get the input by its value
System.out.println(form.getInputByValue("Save as XML").asXml());

Categories

Resources