How to find the exact xpath of an element (link) in an webpage - selenium

Initially I tried with below code:
WebElement admin = driver.findElement(By.xpath("//a[text()='Users']"));
and then also with
WebElement usrs = driver.findElement(By.xpath("//html/body/div[2]/div[3]/div[1]/form/div[4]/div[2]/div[1]/a[linktext()='Users']"));
The above codes didn't identify the object (link) in web page.
Please help me to resolve this issue.!

Try for the first 'a' element containing 'Users'.
WebElement admin = driver.findElement(By.xpath("//a[contains(text),'Users']"));
or for exact match
WebElement admin = driver.findElement(By.xpath("//a[.='Users']"));
and
"//body/div[2]/div[3]/div[1]/form/div[4]/div[2]/div[1]/a[contains(text),'Users']"

If you're going the xpath route, make it easy on yourself. Inspect element with Chrome then right click on the element in the chrome console and "copy xpath". That will give you the exact xpath and you don't have to worry about any "contains" or anything else. That's what the [1] is for.

Related

Unable to recognize Element with relative xpath or other locator

I am facing an issue where I am unable to locate Element on webpage with any type of locator expect Absolute xpath. Here are details:
URL : https://semantic-ui.com/modules/dropdown.html#selection
Required Element Screen shot:
Manually created Xpath Screen shot( Please note that I am able to recognize Element in web application with manually created xpath but Same xpath is not working in selenium code)
But Same xpath is not working in selenium script.
PLEASE NOTE THAT I AM ABLE TO IDENTIFY SAME OBJECT WITH Absolute xpath
Please help to me to understand reason for this.
Here is code:
public static WebDriver driver;
public static void main(String[] args) {
driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://semantic-ui.com/modules/dropdown.html");
//Selection
driver.findElement(By.xpath("//div[#class='ui selection dropdown upward']")).click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Female']")).click();
System.out.println("Done");
This may be issue with your first x-path. You may try the following code. It may work.
driver.findElement(By.xpath("//div[#class='ui selection dropdown']").click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Male']").click();
You are missing a preceding wildcard in you driver.FindElement XPath.
Instead of driver.findElement(By.xpath("//div..."));, do driver.findElement(By.xpath("//*div..."));.
Currently, what your code is doing is telling the XPath locator to find a first level div (not easily possible, as the first item is almost always the document body), but the wildcard of "*" tells it that it can look for the div at any level.
As an aside, please edit your answer up top with actual code instead of pictures so others with the same problem can find their solution easier.
Longshot:
You are using Chrome to look at the source, but Selenium is using Firefox.
There is a chance that the source is rendered differently between the two browsers. Specifically, your xpath is relying on an exact match of class. I do know that FireFox is notorious for modifying source output.
I haven't done any testing but I would not be surprised if the class is in a different order and it's failing on an exact match.
There are two solutions if that is the case:
Don't do a single exact match (xpath = "") but instead do a mix of contains joined with && (contains ui && contains selection && dropdown)
Don't rely on the output from the console tab. Instead "View Page Source" and view what is actually being sent instead of what is being interpreted by the browser
Find the dropdown container element firstly, then use it to find self descendant, like option etc.
driver.get("https://semantic-ui.com/modules/dropdown.html");
// find dropdown container element
WebElement dropdownWrapper = driver.findElement(
By.xpath("//div[#class='html']/div[input[#name='gender']]"));
// expand drop down options by click on the container element
dropdownWrapper.click();
// or click the down arrow
dropdownWrapper.findElement(By.css('i')).click();
// select option
dropdownWrapper.findElement(By.xpath(".//div[text()='Female']")).click();
To locate the element with text as Gender and select the option Female you can use the following Locator Strategy :
Code Block :
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://semantic-ui.com/modules/dropdown.html#selection");
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection']")).click();
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection active visible']//div[#class='menu transition visible']//div[#class='item' and contains(.,'Female')]")).click();
System.out.println("Gender Female selected.");
Console Output :
Gender Female selected.
This might be helpful to clearify how selectors are working in general:
.(dot): Dot at starting represents the current node. It tells us that the processing will start from the current node.
. .(double dot): It will select parent of current node. For example, //table/. . will return div element because div is the parent of table element.
‘*’: is used to select all the element nodes descending from the current node. For example:
/table/*: It will select all child elements of a table element.
//*: It will select all elements in the document.
//*[#id = ‘username’]: It will select any element in document which has an attribute named “id” with the specified value “username”.
#: It represents an attribute which selects id, name, className, etc. For example:
#id: It will select all elements that are defined with the id attribute in the document. No matter where it is defined in the document.
//img/#alt: It will select all the img elements that are defined with the #alt attribute.
//td[#*]: It will select all td elements with any attribute.
Here is a link to the article:
https://www.scientecheasy.com/2020/07/selenium-xpath-example.html/

Selenium Webdriver: cssselector

I am trying to do SignIn for this. In it click on 'SignIn' which I have done it successfully. Now when trying to type in Username/Password using Xpath it shows exception which says
Exception in thread "main"
org.openqa.selenium.ElementNotVisibleException: element not visible
code is :-
driver.findElement(By.xpath(".//*[#id='load_form']/fieldset[1]/input")).sendKeys("test123");
driver.findElement(By.xpath(".//*[#id='load_form']/fieldset[2]/input")).sendKeys("test123");
I know this Xpath is same as used in SignUp form, so what are the other ways to locate these two fields? How we can use it by using cssselector?
Thanks for the help in advance.
Go One Level up on finding the relative xpath with
//div[#id='login']/form[#id='load_form']//input[#name='username']
//div[#id='login']/form[#id='load_form']//input[#name='password']
Try this
//For Username
driver.findElement(By.xpath("(//input[#name='username'])[2]")).sendKeys("username test");
//or
driver.findElement(By.cssSelector("#login > #load_form > fieldset > input[name='usernam']")).click();
//For password
driver.findElement(By.xpath("(//input[#name='password'])[2]")).sendKeys("password test");
//or
driver.findElement(By.cssSelector("#login > #load_form > fieldset > input[name='password']")).click();
the above codes are working for me.
There are basically two elements found by provided xpath, and it works with first found element which is invisible as your exception saying, you should try using cssSelector as below :-
driver.findElement(By.cssSelector("div#login input[name = 'username']")).sendKeys("test123");
driver.findElement(By.cssSelector("div#login input[name = 'password']")).sendKeys("test123");
Note:- For learning about cssSelector follow this url and for xPath follow this url
I'm suggesting you before selenium execution with the locator you need to sure that using locator is correct and returns single or multiple element at your browser console by pressing f12. for verify xPath you should use $x("your xpath expression") and for cssSelector you should use document.querySelector("your css selector expression")..
Hope it will help you..:)

Selinium web driver- Unable to locate href

I trying to locate a link "Taschen" in the below code(<a data-flyout-target="handbags" title="Taschen" href="#">Taschen</a>) using selinium webdriver. Could anyone please guide me
<a data-flyout-target="handbags" title="Taschen" href="#">Taschen</a>
Here are your choices:
By.className
By.cssSelector
By.id
By.linkText
By.name
By.partialLinkText
By.tagName
By.xpath
So assuming that "Taschen" is partial link text
WebElement aLink = driver.findElement(By.partialLinkText("Taschen"));
If you haven't bothered with page loads and proper implicit waits then this might work better
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement aLink = wait.until(
ExpectedConditions.elementToBeClickable(By.partialLinkText("Taschen"))
);
aLink.click();
You are not using java? Update your question to show your code and add a language tag to your question. Your brain isn't a network connected device and we only know what you tell us. :-)
You can also use the XPath as below:-
//a[#title='Taschen']/text()
Code will be as below:-
WebElement tash = driver.findElement(By.xpath("Taschen"));
If you need to get the text then you can use :-
String tash = driver.findElement(By.xpath("Taschen")).getText();
You can also use the contains function in XPath
//a[contains(.,'Taschen')]
Hope it will help you :)

selenium webdriver code to click on 'Album' in facebook

I am not able to click on 'Albums' in Facebook.
The HTML is Albums how to locate the element 'Albums' in selenium web driver.
I tried with using driver.findelement(By.xpath(span[#class="_3sz"]) showing error as element not found
And, the html looks the following:
<span class="_3sz">Albums</span>
If I am understanding your problem correctly then that xpath you mentioned returns more than one elements. Use a text based search which is more easier and specific.
driver.findelement(By.xpath("//*[.='Albums']").click();
And, here . is used to directly point to the parent element. Additional wait might be needed to wait for the element to interact. Also, I am assuming you are trying to click the element.
EDIT
Driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
Driver.Navigate().GoToUrl("http://www.facebook.com");
Driver.Manage().Window.Maximize();
Driver.FindElement(By.CssSelector("#email")).SendKeys("your email");
Driver.FindElement(By.CssSelector("#pass")).SendKeys("your pass");
Driver.FindElement(By.CssSelector("[type='submit'][value='Log In']")).Click();
Driver.FindElement(By.CssSelector(".fbxWelcomeBoxName")).Click();
Driver.FindElement(By.XPath("//*[.='Photos']")).Click();
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[.='Albums']")));
Driver.FindElement(By.XPath("//*[.='Albums']")).Click();
By albumname = By.XPath("//strong[.='2014']"); //this should be your album name. In my case it's 2014
wait.Until(ExpectedConditions.ElementExists(albumname));
Driver.FindElement(albumname).Click();
wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".fbPhotoAlbumHeader.fbPhotoAlbumOptionsPresent [type='file']")));
Driver.FindElement(By.CssSelector(".fbPhotoAlbumHeader.fbPhotoAlbumOptionsPresent [type='file']")).SendKeys(#"D:\Users\Saifur\Desktop\FacebookPicture\150232_585410621540701_1836495431_a.jpg");
wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".pvm.phl.footerBox.uiBoxWhite")));
Driver.SwitchTo().ActiveElement();
wait.Until(ExpectedConditions.ElementExists(By.CssSelector("[name='postPhotosButton']")));
Driver.FindElement(By.CssSelector("[name='postPhotosButton']")).Click();
Notice mine is C#
It always best practice to follow this sequence while selecting elements.
1) ID
2) CSS
3) XPath (This will have some issues with different browsers specially IE)
In this case, considering this is no other span class with same name. It would have work like this "span._3sz". Simple and powerful.

how to locate an element to perform a click

I'm trying to navigate in site: http://startupnationbook.com/startup-map
I want to click on link of Startups, however I'm not able to locate the element.
I tried:
elem = driver.findElement(By.xpath("//a[contains(text(),'Startups')]"));
and
elem = driver.findElement(By.xpath("//*[#id='listtoggle' and contains(text(),'Startups')]"));
In both cases I get: "Unable to locate element" error
What is wrong in my expressions and how can I locate the element to perform a click.
The map is in an iframe, you're probably not telling Selenium to look in there. I would also look for the span tag, and since the id listtoggle is used many times (poor design, making it worthless), just look for contains Startups.
// Also should probably use a wait here, in case the page takes too long to load
chromeDriver.switchTo().frame(chromeDriver.findElement(By.tagName("iframe")));
WebElement elem = chromeDriver.findElement(By.xpath("//span[contains(text(),'Startups')]"));
You can do like below :
WebDriver driver = new FirefoxDriver();
driver.get("http://startupnationbook.com/");
driver.findElement(By.xpath(".//*[#id='main-nav']/li[5]/a")).click();
Hope this will work. I have tested.