How do I increment value of img path when said path looks like this?
//ab[x]/img
X value increasing by 1 and has a limit of 50.
Trying to write a test case on how to click on several images on website.
Edit: Just wanted to add that I'm just starting with Selenium IDE and using standart commands.
Solution 1: Format your xpath path selector
for(int i=1; i<=numberOfImages; i++) {
String path = String.format("//ab[%d]/img", i);
WebElement image = driver.findElement(By.xpath(path));
if(image != null) {
image.click();
}
}
Solution 2: Select all elements that "//ab/img" returns and iterate over them.
String path = "//ab/img";
List<WebElement> imgElements = driver.findElements(By.xpath(path)); //notice the plural
for(WebElement image : imgElements) {
image.click();
}
Related
In selenium 2.0, i am trying to get the list of drop down values and to print it. How to do this? I am trying below:
for (int i = 1;i<=13;i++)
{
WebElement values=driver.findElement(By.xpath("//li[#rel='i']/a/span[#class='pull-left']"));
System.out.println(values);
}
#rel= '1', '2' should go like this.. so that i can print all the values.
But this is not working.. How to use the 'i' in this element.
Thanks
Instead of hard coding no of options value you can get that dynamically.
List<WebElement> options = driver.findElements(By.xpath("//ul/li/a/span[#class='pull-left']"));
//iterate above list to get all option values
for(WebElement eachOption : options) {
System.out.println(eachOption.getText());
}
Some how i managed to get this..
for (int i = 1;i<=13;i++) {
//System.out.println("//li[#rel=" + i +"]/a/span[#class='pull-left']");
String values=driver.findElement(By.xpath("//li[#rel=" + i +"]/a/span[#class='pull-left']")).getText();
System.out.println(values); }
Is there a way to count the number of elements that isn't equal to 0.00?
For example, the code is
<div id="average_2123" style="font-size:20px; ">0.00</div>
<div id="average_2124" style="font-size:20px; ">23.53</div>
<div id="average_2125" style="font-size:20px; ">0.00</div>
How can I count the element so it's only 1 since only one of them has a score?
I want to do this on PHPUnit. I can also do it on Selenium IDE because I can convert it to PHPUnit
you will have to write custom code. I am writing java pseudocode. hope you can understand and convert
List<WebElements> ElemList = Webdriver.FindElements(By.Xpath("//div")
for (i = 0; i < ElemList.size();i++)
{
WebElement Current =List.getElementAt(i);
String ElemName = current.getAttribute("id");
String text =""
int Count = 0;
if( id.Contains("average"))
{
if( !id.getAttribute("value").equals("0.00")
{
count++;
}
}
}
A better approach can be as mentioned below. Im writing the code in Java:
List<WebElement> elemList = driver.findElements(By.cssSelector("div[id^='average']"));
List<WebElement> filteredElements = new ArrayList<WebElement>();
for (WebElement element : elemList) {
if (Long.parseLong(element.getText()) > 0.00)
filteredElements.add(element);
}
This will be find all the elements whose "id" attribute starts with "average".
Also here i am converting the text to long and then comparing whether its grater than 0.00
The filteredEleemnts are the elements which have value greater than 0.00
I want to check the number of characters I can insert in a text field, and was thinking of using 'for loop' but it would not help as Selenium tries to insert more than required character the field will not accept but test goes on without any failure, so is there a way to get character count of the text field?
Would this work?
final String myLongString = "Something horrrrribly looooong";
final int longStringLength = myLongString.length();
// assuming driver is a healthy WebDriver instance
WebElement elem = driver.findElement(By.id("myInput"));
elem.sendKeys(myLongString);
// it's possible that you'll first need to lose focus on elem before the next line
int realLength = elem.getValue().length();
assertEquals(longStringLength, realLength);
Using Protractor I captured the actual text in the field and then did a forloop to count each letter.
element(by.css('elementPATH')).getAttribute('value').then(function(words){
//forloop to count each word
var x = 0
for(var i = 0; i < words.length; i++) {
x = x + 1;
};
//check condition
expect(x).toBe(200);
return true;
});
Let me know if this helps.
I have a piece of HTML like this:
<a href="/something">
Title
<span>Author</span>
</a>
I got a WebElement that matches this HTML. How can I extract only "Title" from it? Method .getText() returns "Title\nAuthor"...
You can't do this in the WebDriver API, you have to do it in your code. For example:
var textOfA = theAElement.getText();
var textOfSpan = theSpanElement.getText();
var text = textOfA.substr(0, textOfA.length - textOfSpan.length).trim('\n');
Note that the trailing newline is actually part of the text of the <a> element, so if you don't want it, you need to strip it.
Here is the method developed in python.
def get_text_exclude_children(element):
return driver.execute_script(
"""
var parent = arguments[0];
var child = parent.firstChild;
var textValue = "";
while(child) {
if (child.nodeType === Node.TEXT_NODE)
textValue += child.textContent;
child = child.nextSibling;
}
return textValue;""",
element).strip()
How to use in this:
liElement = driver.find_element_by_xpath("//a[#href='your_href_goes_here']")
liOnlyText = get_text_exclude_children(liElement)
print(liOnlyText)
Please use your possible strategy to get the element, this method need an element from which you need the text (without children text).
If using Python:
[x['textContent'].strip() for x in element.get_property('childNodes') if isinstance(x, dict)]
Where element is your element.
This will return ['Title', ''] (because there are spaces after span).
you can use jsexecutor to iterate the child nodes, trap the textNode 'Title' and then return its content like below
WebElement link = driver.findElement(By.xpath("//a[#href='something']"));
JavascriptExecutor js = ((JavascriptExecutor)driver);
String authorText = (String) js.executeScript("for(var i = 0; i < arguments[0].childNodes.length; i++) {
if(arguments[0].childNodes[i].nodeName == \"#text\") { return arguments[0].childNodes[i].textContent; } }", link);
The javascript code block above iterates both textNode ('Title') and SPAN ('Author') but returns only the text content of textNode.
Note: Previous to this, I have tried including text node in xpath like below, but webdriver throws invalidselector exception as it requires element not textnode
WebElement link = driver.findElement(By.xpath("//a[#href='something']/text()"));
Verify the element present for "//a[normalize-space(text())=Title]". It will return true if the text present inside 'a' tag is 'Title'.
Is there a way in Selenium RC to get the id from the xpath?
If I have the xpath
/html/body/div/div//input
I want to get the id of all the nodes associated to the xpath
You can use getAttribute in combination with getXpathCount.
A Selenium 1 example in Java would be:
int inputs = selenium.getXpathCount("/html/body/div/div/descendant::input").intValue();
for (int i=1; i<=inputs; i++) {
System.out.println(selenium.getAttribute("/html/body/div/div/descendant::input[" + i + "]#id"));
}
A Selenium 2 example in Java would be:
List<WebElement> inputs = driver.findElements(By.xpath("/html/body/div/div/descendant::input"));
for (WebElement input : inputs) {
System.out.println(input.getAttribute("id"));
}
You can get that by running a javascript, using this.browserbot.findElement('/html/body/div/div//input'):
Of course, this depends on the source language, but it would be something like this (in perl, untested):
#first count the number of inputs with ids
my $count = $selObj->get_xpath_count('/html/body/div/div//input[#id]');
#build a javascript that iterates through the inputs and saves their IDs
my $javascript;
$javascript .= 'var elements = [];';
$javascript .= "for (i=1;i<=$count;i++)";
$javascript .= " elements.push(this.browserbot.findElement('/html/body/div/div/input['+i+']').id);";
#the last thing it should do is output a string, which Selenium will return to you
$javascript .= "elements.join(',');";
my $idString = $selObj->get_eval($javascript);
I always thought there should be a more direct way to do this, but I haven't found it yet!
EDITED based on the comments, the for loop count should start from 1 and include $count, also the findElement line only needs one forward-slash before input.
EDIT2 Adding a completely different idea based on further comments:
Selenium's javascripts that get attached to every page include a function called eval_xpath that returns an array of DOM elements for a given query. Sounds like what you want?
Here's what I think the javascript would look like (again, untested):
var elements = eval_xpath('/html/body/div/div//input',this.browserbot.getCurrentWindow().document);
var results = [];
for (i=0;i<elements.length;i++){
results.push(elements[i].id);
}
results.join(',');