2014-12-05 13 views
21

Nel modulo Python selenio, una volta che ho un oggetto WebElement posso ottenere il valore di uno dei suoi attributi con get_attribute():Web driver al selenio: come trovo TUTTI gli attributi di un elemento?

foo = elem.get_attribute('href') 

Se l'attributo di nome 'href' non esiste, viene restituito None.

La mia domanda è, come posso ottenere un elenco di tutti gli attributi di un elemento? Non sembrano essere i metodi get_attributes() o get_attribute_names().

risposta

36

È non è possibile utilizzando un API di selenio WebDriver, ma è possibile execute a javascript code to get all attributes:

driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element) 

Demo:

>>> from selenium import webdriver 
>>> from pprint import pprint 
>>> driver = webdriver.Firefox() 
>>> driver.get('https://stackoverflow.com') 
>>> 
>>> element = driver.find_element_by_xpath('//div[@class="network-items"]/a') 
>>> attrs = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element) 
>>> pprint(attrs) 
{u'class': u'topbar-icon icon-site-switcher yes-hover js-site-switcher-button js-gps-track', 
u'data-gps-track': u'site_switcher.show', 
u'href': u'//stackexchange.com', 
u'title': u'A list of all 132 Stack Exchange sites'} 

Per completezza, una soluzione alternativa potrebbe essere quella di ottenere il tag outerHTML e analizzare gli attributi utilizzando un parser HTML. Esempio (utilizzando BeautifulSoup):

>>> from bs4 import BeautifulSoup 
>>> html = element.get_attribute('outerHTML') 
>>> attrs = BeautifulSoup(html, 'html.parser').a.attrs 
>>> pprint(attrs) 
{u'class': [u'topbar-icon', 
      u'icon-site-switcher', 
      u'yes-hover', 
      u'js-site-switcher-button', 
      u'js-gps-track'], 
u'data-gps-track': u'site_switcher.show', 
u'href': u'//stackexchange.com', 
u'title': u'A list of all 132 Stack Exchange sites'} 
+0

Qualsiasi idea del perché questo non è stato incluso nelle specifiche W3C? Sembra miope lasciare questo fuori http://www.w3.org/TR/webdriver/#get-element-attribute – raven

+0

@raven non è sicuro, potrebbe essere solo che non è ampiamente utilizzato. Molto più spesso un utente vorrebbe ottenere un singolo attributo .. buona domanda però, grazie. – alecxe

+1

Alternativa: lxml element.attrib restituisce un bel dizionario utilizzabile con tutti gli attributi. – Sandeep

3

Il seguente ottiene un elenco di tutti gli attributi e la loro (a volte tradotto in stringhe) i valori per me, utilizzando i PhantomJS o conducente Chrome almeno:

elem.get_property('attributes')[0] 

To prendi semplicemente i nomi:

x.get_property('attributes')[0].keys() 
1

Ecco il mio tentativo di risposta. L'ho provato solo nella casella di ricerca della home page di Google. Ho usato la risposta di @ alecxe sopra a 'outerHTML' Avendo ottenuto l'html, ho usato un'espressione regolare ([a-z]+-?[a-z]+_?)='?"? per abbinare i nomi degli attributi. Penso che la regex dovrebbe essere modificata per abbinare un numero crescente di casi. Ma il nome essenziale di cui abbiamo bisogno è "qualunque cosa sia dietro il segno di uguale".

dato un webElement

def get_web_element_attribute_names(web_element): 
    """Get all attribute names of a web element""" 
    # get element html 
    html = web_element.get_attribute("outerHTML") 
    # find all with regex 
    pattern = """([a-z]+-?[a-z]+_?)='?"?""" 
    return re.findall(pattern, html) 

test sul codice qui sotto

import re 
from selenium import webdriver 

driver = webdriver.Firefox() 
google = driver.get("http://www.google.com") 

driver.find_element_by_link_text("English").click() 
search_element = driver.find_element_by_name("q") 
get_web_element_attribute_names(search_element) 

uscita:

Problemi correlati