Python Selenium: Find object attributes using xpath

62,475

Solution 1

I finally used get_attribute("value") as:

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

Solution 2

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

Share:
62,475

Related videos on Youtube

root
Author by

root

Getting started with python. `

Updated on June 16, 2020

Comments

  • root
    root about 4 years

    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.

    • Andy Hayden
      Andy Hayden almost 12 years
      perhaps this is a silly suggestion but does using raw strings fix: r"//*[@type='submit']/@value" ?
    • avasal
      avasal almost 12 years
      have you tried something like driver.find_element_by_xpath("//a[contains(text(),'Search')]‌​").click()
    • RanRag
      RanRag almost 12 years
      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 ']
    • root
      root almost 12 years
      @ hayde -- raw string doesnt't fix it.
    • root
      root almost 12 years
      @ 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
    root almost 12 years
    @ Kaipa -- your update is also the closest thing i found. However. There shoul be 'find_element' not elements or a for loop if using elements.
  • Catbuilts
    Catbuilts over 7 years
    @Jayy: yeah, It worked ! you're right. find_elements_by_xpath() function just tries to get an element, not an attribute. So, I got an errror when I want It returns an attribute. I just put get_attribute() following, then done. Thks !