I am trying to click on an element using partial xpath. I can't use ID because there are more than one elements with the same ID. I know my xpath is correct because when I enter it in firepath it highlights the correct element.
Here is my HTML code:
<div class="acme_color_swatches">
<div class="acme_color_swatch " data-color="#CC0000" style=" background-color:#CC0000"></div>
<div class="acme_color_swatch " data-color="#F9F9F9" style=" background-color:#F9F9F9"></div>
<div class="acme_color_swatch" data-color="#990000" style=" background-color:#990000"></div>
<div class="acme_color_swatch" data-color="#FAFAC5" style=" background-color:#FAFAC5"></div>
<div class="acme_color_swatch selected" data-color="#333333" style=" background-color:#333333"></div>
<div class="acme_color_swatch " data-color="#F2F2F2" style=" background-color:#F2F2F2"></div>
<div class="acme_color_swatch " data-color="#F7F7F7" style=" background-color:#F7F7F7"></div>
<div class="acme_color_swatch" data-color="#CB0000" style=" background-color:#CB0000"></div>
<div class="acme_color_swatch " data-color="#DDDDDD" style=" background-color:#DDDDDD"></div>
<div class="acme_color_swatch " data-color="#E2F2FF" style=" background-color:#E2F2FF"></div>
<div class="acme_color_swatch" data-color="#F5F5F5" style=" background-color:#F5F5F5"></div>
<div class="acme_color_swatch" data-color="#0069FF" style=" background-color:#0069FF"></div>
Here is my selenium code:
driver.findElement(By.xpath("//div[contains(#style, '#0069FF')]")).click();
Here is the error I am getting:
FAILED: main
org.openqa.selenium.NoSuchElementException: Unable to locate element {"method":"xpath","selector":"//div[contains(#style, '#0069FF')]"}
What am I doing wrong?
I find the cssSelector easier and more reliable and it will likely work for you in this case. You can try something like this:
By.cssSelector("div[style$='#0069FF']");
This will find any div that has a style-attribute that ends with #0069FF.
You could use
driver.findElement(By.cssSelector("div[data-color='#0069FF']")).click();
It's looking for a DIV that has a data-color attribute = #0069FF.
I was able to resolve this issue by myself. Here is what I did:
driver.findElement(By.xpath("//div[contains(#style, ' background-color:#FAFAC5')]")).click();
There is a space between the hyphen and the ' background-. This was causing all of the grief.
These div are an array, so you can use:
driver.findElement(By.xpath("(//*[#class='acme_color_swatch'])[11]")).click();
to click on the 11th element which class is acme_color_swatch.
I think you need to use some logic here. Try to find the all webelements with classname and then find your specific color. Try the code below:
public void Findelement() throws InterruptedException {
WebElement element = driver.findElement(By.classname("acme_color_swatch"));
String Color = "#0069FF";
if (element.contains(Color)){
element.click();
}
}
Related
element code:
<div class="col col-2"><div class="v-input v-input--is-focused theme--light v-text-field v-text-field--is-booted v-select primary--text"><div class="v-input__control"><div role="button" aria-haspopup="listbox" aria-expanded="false" aria-owns="list-65" class="v-input__slot"><div class="v-select__slot"><label for="input-65" class="v-label v-label--active theme--light primary--text" style="left: 0px; right: auto; position: absolute;">Narystė</label><div class="v-select__selections"><input id="input-65" readonly="readonly" type="text" aria-readonly="false" autocomplete="off"></div><div class="v-input__append-inner"><div class="v-input__icon v-input__icon--append"><i aria-hidden="true" class="v-icon notranslate material-icons theme--light primary--text">arrow_drop_down</i></div></div><input type="hidden" value="[object Object]"></div><div class="v-menu"><!----></div></div><div class="v-text-field__details"><div class="v-messages theme--light primary--text"><div class="v-messages__wrapper"></div></div></div></div></div></div>
in screen you can see, that entered xpath is only one.
Here is code, where i have entered the same xpath, but getting error like this:
private static final By naryste = By.xpath("//*[contains(#class,'v-label v-label--active theme--light primary--text') and contains(text(),'Narystė')]");
#Step("Pasirenkame juridinio asmens organizaciją iš reikšmių sąrašo")
public createOrganization selectMembership() {
button.click(naryste);
return this;
}
Selenium webdriver can't find this xpath:
Find element :By.xpath: //*[contains(#class,'v-label v-label--active theme--light primary--text') and contains(text(),'Narystė')]
P.S. the same problem if i choose other elements
AND this (selenium can't find)
To locate the element you can use the following Locator Strategy:
Using xpath:
By.xpath("//label[starts-with(#for,'input') and contains(.,'Narystė')]");
PS: Do add some waits before invoking the click()
I am trying to extract Main Text1 and Main Text2 from below DOM structure.
<div class="origination">
<div class="origin">
<h3>
Main Text1
<span class="info">Test1</span>
</h3>
<div class="test">
</div>
</div>
<div class="origin">
<h3>
Main Text2
<span class="info">Test2</span>
</h3>
<div class="test">
</div>
</div>
</div>
I have used below xpath with text() to identify header without span
#FindBy(xpath = ".//*[#id='origination']/div[*]/h3/text()")
List<WebElement> content;
I am trying to print header element without span using below code
for (WebElement element: content){
System.out.println("Header" + element.getText());
}
But I am getting error:
org.openqa.selenium.NoSuchElementException: Timed out after 15 seconds. List elements not found
However, when I used the same XPath on the firepath elements get highlighted in the DOM structure but not on to the page.
Here is the answer.
spanText = element.findElement(By.xpath("//span[#class='info']")).getText()
element.getText().Replace(spanText, string.Empty);
I am writing a test in Webdriver C# with Nunit. I have a search results page loaded with a list of products with images. I want to click the 1st image in the results.
I have tried using the Xpath (I used firepath to get this value)
[FindsBy(How = How.XPath, Using = "html/body/form/div[2]/div[4]/div/div[2]/p")]
private IWebElement ProductImage_xpath {get; set; }
When it runs it says:
Could not find element by XPath.
I would like to use CSS selector if possible as that is faster than finding by Xpath.
What syntax could I use to locate the image from the code snipped below?
Note: the hyperlinks are dynamic, I don't want to use the href.
public SearchResultsPage clickProduct_Image()
{
ProductImage_xpath.Click();
Console.Out.WriteLine("ProductImage = " + ProductImage_xpath.Text);
return new SearchResultsPage(Driver);
}
The Code snippet:
<div id="main" class="nav_redesign s-left-nav-rib-redesign" data-page-construction="aui" skeleton-key="results--searchTemplate listLayout so_gb_en --left-nav--shopping-engine">
<div id="topStatic">
<div id="top">
<div id="topAmabot"> </div>
<div id="searchTemplate" class="searchTemplate listLayout so_gb_en ">
<div id="topDynamicContent">
<div id="rightContainerATF">
<div id="rightResultsATF">
<div id="widthPreserver"></div>
<div id="centerPlus">
<div id="rhsAjax"></div>
<div id="resultsCol" class="">
<div id="centerMinus" class="">
<div id="atfResults" class="list results apsList">
<div id="result_0" class="fstRow prod celwidget" name="1780974728">
<div class="linePlaceholder"></div>
<div class="image imageContainer">
<a href="http://testerServer1co.uk/SpaceExplorer/dp/1780974728/ref=sr_1_1?ie=UTF8&qid=1409311161&sr=8-1&keywords=planets+1">
<div class="imageBox">
<img class="productImage cfMarker" alt="Product Details" src="http://ecx.images-test.com/images/I/51iYWWt1BqL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU02_AA160_.jpg" onload="viewCompleteImageLoaded(this, new Date().getTime(), 16, false);">
</div>
Xpath is very very bad choice to find element on the page =). As you said better use css selector. I don't know how your image presents on the page, but i'll write possible variants, choose the best one. So, using css selectors to find your image:
1. You can find any element using it's class
//will find "div class="image imageContainer""
driver.findElement(By.Css(".imageContainer"))
2. Combine searching by class and find first "a" child in that div
driver.findElement(By.css(".imageContainer > a"))
3.Find element using known attribute
driver.findElement(By.css("img[alt='Product Details']"))
4. Find element by ID
driver.findElement(By.Css("#atfResults"));
//or
driver.findElement(By.Id("atfResults"));
Well, it will be enough for you, i think. If you have any questions, you are welcome.
1) I have a dialog on my web page having 2 buttons, Yes & No.
2) IDs of these buttons are dynamicaly changing every time.
3) How to handle this situation and click on Yes button?
4) Both buttons, Yes & No, have same classname 1.e. rwInnerSpan
5) Here is the Xpath for Yes button
(.//*[#id='confirm1381468352443_content']/div/div[2]/a[1]/span/span)
the part 1381468352443 in xpath is dynamically changing.
Below is the source code of page
`
<tr class="rwTitleRow">
<tr class="rwContentRow">
<td class="rwCorner rwBodyLeft"> </td>
<td class="rwWindowContent" valign="top">
<iframe frameborder="0" name="confirm1381468352443" src="javascript:'<html></html>';" style="width: 100%; height: 100%; border: 0px none; display: none;" tabindex="0">
<div id="confirm1381468352443_content">
<div class="rwDialogPopup">
<div class="rwDialogText">
<div>
<a class="rwPopupButton" href="javascript:void(0);" onclick="$find('confirm1381468352443').close(true);" tabindex="-1">
<span class="rwOuterSpan">
<span class="rwInnerSpan">Yes</span>
</span>
</a>
<a class="rwPopupButton" href="javascript:void(0);" onclick="$find('confirm1381468352443').close(false);" tabindex="-1">
<span class="rwOuterSpan">
<span class="rwInnerSpan">No</span>
</span>
</a>`
Thanks in Advance !!
You can directly check for the text in your Xpath:
driver.findElements(By.xpath("//a[#class='rwPopupButton']/span/span[contains(text(), 'Yes')]"))
There is a way to locate objects using partial link text, so you can try this:
driver.findElement(By.partialLinkText("Yes")).click();
Plain By.linkText may not work because of additional spaces or characters in the link.
You can click on the button based on the Text. Following method will give you a webelement based on the class locator and text.
WebElement getElementBasedOnClassAndText(String classLocator, String text){
List<WebElement> elements = driver.findElements(By.className(classLocator))
for(WebElement element : elements){
if(element.getText().contentEquals(text)){
return element
}
}
Assert.fail("Unable to find any element with the said Text")
}
Once you get the element you can take any action on it.
Since it is dynamic I would look for the changed name:
//Find the dynamicly created ID
String dynamicID = driver.findElement(By
.xpath("//iframe[contains(#name,'confirm')]")
.getAttribute("name");
//Use that ID to find the Yes option
driver.findElement(By
.xpath("//*[#id='"+dynamicID +"_content']/div/div[2]/a[1]/span/span")
.click();
I wanted to click the date from calendar popup which is inside iframe. I have written below selenium code which throwing unable to locate the element error. Please help me to write correct xpath or selenium code. I am new to Selenium
selenium code:
WebElement iframe =driver.findElement(By.id("NewsSearchDateToInput_selector_iframe"));
driver.switchTo().frame(iframe);
//clicking on date 3
driver.findElement(By.xpath("//div[3][#class='daysNumbersStyles']")).click();
Error: unable to locate the element "//div[3][#class='daysNumbersStyles']"
Html tags:
<iframe id="NewsSearchDateToInput_selector_iframe"
class="dateTimeSelectorContainerStyle altFlexibleContainer"
src="javascript:false;"
style="left: 1216px; top: 245px; width: 249px; height: 207px;
display: block;"/>
<div class="dateTimeSelectorContainerStyle altFlexibleContainer"
style="top: 245px; left: 1216px; display: block;">
<div class="top">
<div class="content">
<div class="dateSelectorHeader">
<div class="dateSelectorBody">
<div class="yearMonthSelectorStyle">
<div id="NewsSearchDateToInput_selector_monthSelector" class="monthSelectorListStyle">
<div class="daysStyle">
<div>
<div class="daysNumbersDivStyle">
<div class="daysNumbersStyles">1</div>
<div class="daysNumbersStyles">2</div>
<div class="daysNumbersStyles">3</div>
does it help ? //div[#class='daysNumbersStyles'][3]
Try this after getting in to frame:
driver.findElement(By.xpath("//div[text()='3']").click();
Edit:
For To selector:
driver.findElement(By.xpath("//*[#id='NewsSearchDateToInput_selector_monthSelector']//div[text()='3']").click();
For From selector:
driver.findElement(By.xpath("//*[#id='NewsSearchDateFromInput_selector_monthSelector']//div[text()='3']").click();