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")
Related videos on Youtube
Comments
-
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 almost 12 yearsperhaps this is a silly suggestion but does using raw strings fix:
r"//*[@type='submit']/@value"
? -
avasal almost 12 yearshave you tried something like
driver.find_element_by_xpath("//a[contains(text(),'Search')]").click()
-
RanRag almost 12 yearsWhen 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 almost 12 years@ hayde -- raw string doesnt't fix it.
-
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 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 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 !