22
votes

I am new to xpath, trying to get value of the "value" using xpath:

<input type="submit" value="  Search  " class="long searchButton" style="width:190px !important;">

while it is easy to find element by "type="submit" like:

browser.find_elements_by_xpath("//*[@type='submit']")

I haven't been able to figure out how to get the values I need, as:

browser.find_elements_by_xpath("//*[@type='submit']/@value")

somewhat expectedly gives an error:

expression "//*[@type=\'submit\']/@value" is: [object Attr]. It should be an element

Any ideas how to solve this?

EDIT: The xpath is correct, but it "returns" an obj attribute and as it is not an element, it is not allowed. I can't find a method like get_attr_by_xpath(), or anything similar.

3
perhaps this is a silly suggestion but does using raw strings fix: r"//*[@type='submit']/@value" ? - Andy Hayden
have you tried something like driver.find_element_by_xpath("//a[contains(text(),'Search')]").click() - avasal
When I tried your xpath with lxml it worked fine. I tried lxml.html.fromstring(s).xpath("//*[@type='submit']/@value") and the o/p is [' Search '] - RanRag
@ hayde -- raw string doesnt't fix it. - root
@ RanRag -- yes, xpath seems to be correct, the problem seems to be with "find_elemnts", as object attribute is not an element. However there doesn't seem to be a method like get_attr_by_xpath or anything similar for browser object. - root

3 Answers

38
votes

I finally used get_attribute("value") as:

for i in browser.find_elements_by_xpath("//*[@type='submit']"):
    print i.get_attribute("value")
2
votes

It would be like this

browser.find_elements_by_xpath("//*[@type='submit']/@value").text

Update:

With the function used by you, we can only extract the element not its attribute. To get its attribute, the expression should be something like this

browser.find_elements_by_xpath("//*[@type='submit']").get_attribute("value")

Ref: http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webelement.WebElement.find_elements_by_tag_name

0
votes

I certainly know this was posted over 2 years ago, but I would like to add a little to it which was left out. selenium provides built-in words that could be use to pull the text that is in between the tags or the actual attribute values inside the tags.

${XPATH}    xpath=(//td[@title='mytitle']/../td)[2]     

Here is a quick example:

${THE_NAME}=       Get Text           ${XPATH}