How to create my own xpath on website- Selenium - selenium-webdriver

I'm writing a small application to go on to twitter.com select the login button and then enter username and password.
I've been able to inspect the log in button and copy the XPath from chrome but I've been unsuccessful in create my own XPath from the information given. The XPath used when copied does work but it doesn't look tidy in my code therefore I'm keen to write my own.
WebDriver driver = new ChromeDriver();
driver.get("http://www.twitter.com");
driver.findElement(By.xpath("//*[#id=\"react-root\"]/div/div/div/main/div/div/div[1]/div[1]/div/div[3]/a[2]/div")).click();
Below is what is given when I inspect the log in button.
<div dir="auto" class="css-901oao r-1awozwy r-13gxpu9 r-6koalj r-18u37iz r-16y2uox r-1qd0xha r-a023e6 r-b88u0q r-1777fci r-ad9z0x r-dnmrzs r-bcqeeo r-q4m81j r-qvutc0">
<span class="css-901oao css-16my406 css-bfa6kz r-poiln3 r-bcqeeo r-qvutc0">
<span class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0">Log in</span>
</span>
</div>

You can identify the login button based on his parent unique attributes.
Then using the xpath axe /descendant, to selects all the descendants (children, grandchildren, etc.) of the current node, you can navigate down to the span that has the text Log in
driver.findElement(By.xpath("//a[#data-testid='loginButton']/descendant::span[text()='Log in']")).click();
Or
driver.findElement(By.xpath("//a[#href='/login']/descendant::span[text()='Log in']")).click();
If you want to study the xpath/css selector have a look here: https://devhints.io/xpath

I'm not sure what answer you are looking for so here are several possibilities:
Just give me the codez!
A: Try //a[#data-testid='loginButton']
How do I read the source of a page so that I can craft proper XPath?
A: That comes from experience. As a start, open your devtools and hover around with your mouse to see what element highlights what on the page. Read carefully through the attributes.
Where do I learn proper XPath?
A: Search on the Internet for some tutorials. Personally I started with this one, and then build up from there.

Related

How to click on a deeply buried button in div classes via protractor. No id

I am trying to click a button that is buried in div classes in the code via protractor.
I am pioneering a protractor project for my work and have reached a point where I no longer know what to do. I have a button that is buried in div classes and is not allowing me to click. I have tried using mouseMove to get over to the coordinates of the button, I have tried using the className of the specific button, etc. The button does not have an id. The id is not the issue as I have tried clicking a different button, equally buried in divs, by it's id. I need to know how to get through the layers of divs in order to click the button because the rest of the tests will be dependent on it.
APPLICATION CODE:
::before
<dashboard-label>
<div class="att-topic-analysis-tabs">
<div class="att-button-group">
<button class="btn btn-default btn-lg att-close-topic ng-scope"
role="presentation" tabindex="-1"
ng-click="removeTopic(currentTopic.id)" translate>
Close Topic
</button>
</div>
</div>
PROTRACTOR TEST:
it('Closes Topic Successfully', function(){
//opens the first available topic
openTopic.click();
//checks that the URL contains 'topics' after 5 seconds
browser.wait(proExpect.urlContains('topics'), 5000);
var closeTopic = element(by.className('att-close-topic'));
//browser.wait(proExpect.elementToBeClickable(closeTopicButton), 5000);
console.log(closeTopic);
closeTopic.click();
browser.wait(proExpect.urlContains('home'), 5000);
});
As you can see, the Close Topic button is kind of buried in div classes and the standard click isn't working. Any info would be greatly appreciated
If the closeTopic locator is finding the element, but failing to click it, check to make sure there's only one matching element in the DOM, and that it's visible. My favorite way to check the DOM is just ctrl-F in Chrome inspector and paste the exact CSS that the test is using (.att-close-topic). And to check that what it's getting is visible, use
console.log(closeTopic.isDisplayed());
This can be a big gotcha in protractor, because it doesn't fail (only warns) when there are multiple matches on the page, and it defaults to the first match rather than the first visible match, which drives me nuts, because it's very rare that you want to do anything with a non-visible element on the page.
This will be partly opinion, but just to add a layer to the conversation...
Sometimes the solution to locating a troublesome element on the page is to go back to the developers and make the page more testable. I've seen testers spend hours or days crafting brilliant workarounds to access a stubborn element, and the end result was a fragile, complicated end-to-end test (and aren't they fragile enough already?).
Sometimes a 5-minute conversation with a developer can result in a quick change in the production code (e.g. add a unique ID) that avoids all that effort and yields a much better result, more stable, more simple. But this requires open conversation between the dev and test team, and a culture that values testing as a primary activity enough to make those testability changes to production code that is otherwise working just fine.
This is what you want to read to help you debug why your test doesn't work.
Also, you might want to start adopting await/async since the control flow will go away in the future.
http://www.protractortest.org/#/debugging
try this
var closebutton=element(by.css("[ng-click="removeTopic(currentTopic.id)"]"),
EC = protractor.ExpectedConditions;
Waits for the element to be clickable.checks for display and enable state of button
browser.wait(EC.elementToBeClickable(closebutton), 10000);
now use : closebutton.click();

click method is not working properly in selenium webdriver

i am trying to Automate flipkart website in which i am trying to change address but "add new adress" is not getting clicked i have attached the snapshot
my code is like driver.findElement(By.xpath("//*[#id='ng-app']/div/div[2]/ul/li[2]/div/div[2]/div[2]/div[2]/a/span")).click();
please give the appropriate help
I doesn't look that you are clicking active element, the xpath is //*[#id='ng-app']/div/div[2]/ul/li[2]/div/div[2]/div[2]/div[2]/a/span not correct it clicks on some span.
Use Firepath https://addons.mozilla.org/en-US/firefox/addon/firepath/ to get the xpath.
To ensure that button is clickable Use isDisplayed() and isEnabled() method before clicking on "Add New Address" button, this method return boolean value.
driver.findElement(By.xpath("//*[#id='ng-app']/div/div[2]/ul/li[2]/div/div[2]/div[2]/div[2]/a/span")).isDisplayed();
driver.findElement(By.xpath("//*[#id='ng-app']/div/div[2]/ul/li[2]/div/div[2]/div[2]/div[2]/a/span")).isEnabled();
Also you can verify that element is exist on page or not using below code
if(driver.findElements(byVal).size()!=0){
// Element is present.
}
hope it may helpful to identify cause of issue, why its not clickable.
First and foremost, Use a customized Xpath instead of the one you are using which is extracted directly from the browser. If no customized Xpath can be constructed then try a customized Css or any other locator if possible.
Try to go through the following attempts in order (I hope you can grasp why this is):
1- If .click() still doesn’t work, then keep on changing the values of the attributes you are using to construct your customized xpath, cssSelector, or locator.
2- Use the Actions class.
3- Use JavaScript executioner
4- instead of click(), try using any of: .sendKeys(“\n”). Or .sendKeys(keys.ENTER) or .sendKeys(keys.RETURN)

Not able to click and element using Selenium

I am trying to automate 'Tableau' login screen and download reports flow. Everything works fine till I reach the 'Download' button. The first problem is I am NOT able to right click on the Download button and do an 'Inspect' in Chrome which is weird. I somehow am able to find the xpath by going through the whole page. When i try to click it I get "Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div[2]/div/div[3]/div[4]/span[1]"}".
The code that I am using is mentioned below:
String xPath = "/html/body/div[2]/div[2]/div/div[3]/div[4]/span[1]";
(new WebDriverWait(driver, 20))
.until(ExpectedConditions.elementToBeClickable(By.xpath(xPath)));
driver.findElement(By.xpath(xPath)).click();
The page layout is like this from where I am picking the xpath
<div class="tabToolbarButton tab-widget" style="-webkit-user-select: none; -webkit-tap-highlight-color: transparent; width: 77.4px;">
<span class="tabToolbarButtonImg tab-icon-download"></span>
<span class="tabToolbarButtonText">Download</span></div>
<span class="tabToolbarButtonImg tab-icon-download"></span>
<span class="tabToolbarButtonText">Download</span>
</div>
Any help would be appreciated. What could be the reason for not able to 'Inspect'??
If you are not able to right click on the element, you can still right click anywhere on the page and select Inspect this element. You can then grab little binocular icon(tool tip message-select an element in the page to inspect it) and point it to the desired web element to check the xpath.
1st thing you need to check if you are writing xpath correctly. On a chrome you can do that without any plugin. On the developer window(same window which gets open when you select Inspect Element option), look for Console window and write your xpath as mentioned below and hit Enter.
$x("Write x path here")
for e.g. xpath for google search box
$x("//input[#id='lst-ib']")
I'm not sure why you writing absolute xpath. Its a bad practice. You can write x path for Download button in better way.
e.g.
(//span[#class='tabToolbarButtonText'])
I got the problem. So it seems the web page I was trying to automate has used frames. That is why even after providing the xpath the element was not getting clicked. I had to use 'switchTo.frame' in order to get the frame in focus and then I was able to click the element. Thanks for all the responses.
What I have still not understood is that why I was not able to inspect the element directly but that is a different question.

Cannot find button element on form using Webdriver

I'm having trouble trying to click on on a button within a form.
I've tried xpath, cssselector, className, id, but still cannot find it.
Here's the HTML snippet for the button:
<input type="button" value="Continue" id="ni-reg-btn-register" class="btnNext ni-reg-btn-register">
I'm using WebDriver in Java
Getting this trace:
org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
Command duration or timeout: 30.09 seconds
Frequency: 100%
Browser: Firefox
URL: https://subscription.thetimes.co.uk/webjourney/webj_capturecustomerdetails
I've tried each of the following lines of code one by one (but no luck):
driver.findElement(By.className("btnNext ni-reg-btn-register")).click();
driver.findElement(By.cssSelector("buttons#ni-reg-btn-register.btnNext ni-reg-btn-register")).click();
List<WebElement> buttonlist= driver.findElements(By.className("btnNext ni-reg-btn-register"));
driver.findElement(By.id("ni-reg-btn-register")).click();
driver.findElement(By.xpath("//*[#id="ni-reg-btn-register"]")).click();
I was able to click the Continue Button using the below xpath.
//input[#id='ni-reg-btn-register']
I would suggest trying a WebDriverWait call to wait for the element in question to exist on the page prior to interacting with it. The Java documentation can be found here. It appears that while you are using the correct locator and your page is working, there is a timing issue where Selenium is trying to access the element prior to it being loaded.
EDIT: I was unable to locate an element on the provided page with the supplied id. I assume I am missing a step, but I did a search on the HTML for that page and found nothing.
I dont find the above button on the page link you provided ..
better chk the page link and try to give some wait statement after page load ...
implicit wait would be better or simpli Thread.sleep(2000);

Wrong button is clicked on with a page having two buttons

I'm using Selenium Webdriver to test a web page.
The web page http://www.leaseplan.nl/contact/index.asp has two buttons, one button with button text 'Zoeken' and one with button text 'Verstuur'. I want to click on the button with button text 'Verstuur' either by using XPath or CssSelector with the following code:
driver.FindElement(By.XPath("/html/body/div[3]/div[2]/div[2]/form/fieldset/a/span")).Click();
driver.FindElement(By.CssSelector("fieldset.contact_form > a.button > span.button_center")).Click();
But using the either one of the above lines of code, on the button with text 'Zoeken' is clicked on instead.
This button has quite a similar CssSelector and XPath:
fieldset.header_search a.button span.button_center
/html/body/div[3]/div/form/fieldset/a/span[2]
Does anybody know how to solve this?
Try this out with the cssSelector and tell me if it's work.
For "verstuur" :
By.cssSelector("div.content form a.button")
Solution :
Ok, i've found your problem. Your xpath is good but now, your action on the click submit the first form, so the form with "Zoeken".
onclick="document.forms[0].submit();" // submit the 1st form, the bad one !
Try this :
onclick="document.forms["form"].submit();" // submit the 2nd form, the good one !
//or
onclick="document.forms[1].submit();"
proof : Jsfiddle
xpath for ZOEKEN /html/body/div[3]/div/form/fieldset/a/span[2]
xpath for VERSTUUR /html/body/div[3]/div[2]/div[2]/form/fieldset/a/span[2]
Try this:
driver.FindElement(By.XPath("//span[text()='Verstuur']")).click();
Edit:
I think you want to learn Selenium that's why you are using 3rd party websites. If you really want to learn Selenium find some opensource applications to automate. Here is a good application to automate -
http://sourceforge.net/projects/sugarcrm/files/1%20-%20SugarCRM%206.5.X/FastStack/
Download the latest version and install.
Find more info about the website and selenium stuff here. It's so good..
http://selftechy.com/2011/02/05/introduction-to-selenium-web-application-test-automation-tool
Zoeken: driver.findElement(By.xpath("//div[1]/form/fieldset/a/span[2]")).click();
Verstuur : driver.findElement(By.xpath("//div[2]/form/fieldset/a/span[2]")).click();
Using xpath is easy but slow.

Resources