How can you use "getAttribute" method of WebDriver in HTML structure? - selenium

How can you use "getAttribute" method of WebDriver for the given HTML structure?
<span id=“span1” class=“spanClass” > Option1 </span>
Code trials :
driver.findElement(By.id("span1")).getAttribute("class");
and
driver.findElement.getAttribute(By.id("span1"));
and
driver.findElement("value").getAttribute(By.id("span1"));
and
driver.findElement(By.id("span1")).getAttribute();

your first trial,
driver.findElement(By.id("span1")).getAttribute("class");
looks good, did you try printing that ? if yes, did you get proper output or was there any other error ?
your 2nd code trial
driver.findElement.getAttribute(By.id("span1"));
is invalid, since you can not call getAttribute() like that, it should result in compile time error.
Your 3rd code trial :
driver.findElement("value").getAttribute(By.id("span1"));
is again invalid, you can not find the element with a string input.
your 4th code trial :
driver.findElement(By.id("span1")).getAttribute();
is again invalid, since you are not passing anything in getAttribute();
method. It should again result in compile time error.
Below is an alternative way with xpath :
//span[#id='span1']
and get the id or class attribute like this :
String idAttribute = driver.findElement(By.xpath("//span[#id='span1']")).getAttribute("id");
System.out.println(idAttribute)
or to get class attribute you can do something like this :
String classAttribute = driver.findElement(By.xpath("//span[#id='span1']")).getAttribute("class");
System.out.println(idAttribute)

Related

Robotframework Selenium Library - extract clas sub-element

I need to extract an attribute "sub elemement" after initial selector.
I'm using this syntax as selector:
${first_video}= Get WebElement xpath:(//div[contains(#data-store, 'videoID')])[1]
This correctly give me this single element part:
<div class="alpha" data-store="{"videoID":"1234","playerFormat":"inline","playerOrigin":"video_home","external_log_id":null,"external_log_type":null,"playerSuborigin":"entry_point",
"useOzLive":false,"playOnClick":true,
"videoScrollUseLowThrottleRate":true,"playInFullScreen":false,"type":"video","src":"https:\/\/video.test.com\/v\/a\/123_n.mp","width":320,"height":180,
"videoURL":"https:\/\/www.test.com\/test\/videos\/12345\/","disableLogging":false}" data-sigil="Video">
</div>
My goal is to get the VideoURL attribute.
I've tried with
${first_video_link}= Call Method ${first_video} value_of_css_property data-store.videoURL
but it gaves me empty output.
Is there any specific syntax that I'm missing?
Many Thanks
Get the value of the data-store atrribute:
${val}= Get Element Attribute ${your locator}
It appears to be a proper json, so convert it to a python dictionary and then just access its key:
${as json}= Evaluate json.loads("""${val}""") json
Log To Console The videoURL is ${as json['videoURL']}

How to select one from duplicate tag in page in java in selenium webdriver

I am using Selenium WebDriver and I have number of items on a page and each item on page is a separate form type.
I have saved all of these form elements in a list and I am iterating over every item in an attempt to get the name of the element by using the "alt" attribute.
However when I try to get the "name" attribute from the input element it is always returning the first input tag found on that page, not the name attribute of the element I have currently selected.
The syntax I am using is:
((Webdriver imgtags.get(i)).findelement(By.xpath("//input[#name='qty']")).sendKeys ("100");
I have also tried to get the id from the tag by using:
((Webdriver imgtags.get(i)).getAttribute("id");
It's returning a blank value, but it should return the value of the id attribute in that input tag.
I also tried to get the id by using .bytagname but as id is an attribute it is not accessible
Try:
(driver) findElement(By.xpath("//*[contains(local-name(), 'input') and contains(#name, 'qty')]")).sendKeys("100");
To answer the comment by #rrd: to be honest, I have no idea why OP uses ((Webdriver imgtags.get(i)). I don't know what that is. Normally, I just use driver.findElement[...]
Hoping that he knows what works in his framework :D
Selenium Xpath handling is not fully compliant and it does not always treat // as a synonym of descendant-or-self.
Instead try tweaking your code to use the following Xpath:
((Webdriver imgtags.get(i)).findElement(By.xpath("./descendant-or-self::input[#name='qty']")).sendKeys("100");
This will base your search off the currently selected WebElement and then look for any descendants that have a name attribute with a value of "qty".
I would also suggest storing your imgtags array as an array of WebElement e.g.
List<WebElement> imgtags = new ArrayList<>();
This is a much better idea than casting to WebDriver to be able to use .findElement(). This will cause you problems at some point in the future.

Getting Attribute using xpath in selenium

I have been looking for an XPath code to get the value of the attribute of an HTML element as part of my regression testing. Can anyone please help
the attribute value is dynamic changes for every next webelement
below is the HTML code
<figcaption id="recentVideosvideoname0" data-videono="xZA6FJ32Twe2GQYEuBHJnQ==" title="test for test" class="caption">test for test</figcaption>
i want attribute : data-videono
I have tried something like this
By.xpath(("//div[contains(#id,'recentVideos')]/div/a/figure/figcaption"));
Here is the Answer to your Question:
To retrieve the attribute data-videono you can consider to use the following line of code:
String my_attribute = driver.find_element_by_xpath("//figcaption[starts-with(#id, 'recentVideos') and #title='test for test']").getAttribute("data-videono");
Let me know if this Answers your Question.
Please follow the approach mentioned below:
driver.findElement(By.xpath("//div[contains(#id,'recentVideos')]/div/a/figure/figcaption")).getAttribute("data-videono");
You can get attribute value by using XPath itself.
XPath 1.0
"//div[contains(#id,'recentVideos')]/div/a/figure/figcaption/#data-videono"
Notice the #data-videono at the end of string, which will return attribute value (p.s. it seems like it is base64 encoded data)
I don't know if i got your question, but do you already tried:
String var = driver.frindElemnt(By.xpath("put your xpath in here")).getAttribute("data-videono");

how to get the readonly field value using selenium

I have read only field on Webpage as
<div id="dspIdDescriptionDet-inputEl" class="x-form-display-field" role="input" aria-invalid="false" data-errorqtip="" style="width: 100%;">2010-RR3 XIIIA9 20360726 FLT</div>
When I'm trying to get the display value ("2010-RR3 XIIIA9 20360726 FLT") using getText() or getAttribute("Value") using Webdriver, its fetching nothing.
error on eclipse:
expected:<2010-RR3 XIIIA9 20360726 FLT> but was:<null>
code:
driver.findElement(By.xpath(".//*[#id='dspIdDescriptionDet-i‌​nputEl']")).getAttri‌​bute("value"))
For getting the text of an element which has a unique id try using:
driver.findElement(By.id("dspIdDescriptionDet-inputEl")).getText()
Moving my comment to an answer since it turned out to be the issue...
I would try adding a wait. It may be that the element is present but it takes a bit for the data to populate into the field.

behat fillField xpath giving error?

This line of code:
$this->fillField('xpath','//fieldset[#id="address-container"]/input[#name="address_add[0][city]"]', "Toronto");
Is giving me this error
Form field with id|name|label|value|placeholder "xpath" not found. (Behat\Mink\Exception\ElementNotFoundException)
The reason I want to use xpath in my fillField is because there are actually multiple input[#name="address_add[0][city]"] in my html document. I figure an xpath will let me target specifically the field I want to populate.
What's the best way to fill out just the input[#name="address_add[0][city]"] that is a descendant of fieldset[#id="address-container"] ?
You are not using the method in the wright way.
As i see here xpath is taken as selector.
The method expects 2 parameters:
identifier - value of one of attributes 'id|name|label|value'
value - the string you need to set as value
If you want to use css|xpath then you need to use find method first.
For example:
$this->find('xpath', 'your_selector')->setValue('your_string');
Please note that find might return null and using setValue will result in a fatal exception.
You should have something like this:
$field = find('xpath', 'your_selector');
if ($field === null) {
// throw exception
}
$field->setValue('your_string');
Also your selector could be written as:
#address-container input[name*=city] - this with css
or
//fieldset[#id="address-container"]//input[contains(#name, 'city')] - this with xpath
Make sure you take advantage of your IDE editor when you have any doubts using a method and you should find a php doc with what parameters are expected and what the method will return.
If you are using css/xpath a lot you could override find method to detect automatically the type of selector and to use it like $this->find($selector);
Also you could define another method to wait for the element and to handle the exception in one place, for example waitForElement($selector) that could contain a conditional wait up to 10 seconds and that throws exception if not found.