2014-12-05 2 views
21

, 나는이 WebElement 객체를 일단 나는 get_attribute()와의 속성의 몇개의 값을 얻을 수 있습니다 : Selenium webdriver : 요소의 속성을 모두 찾으려면 어떻게해야합니까? 파이썬 셀레늄 모듈에서

foo = elem.get_attribute('href') 

'HREF'라는 이름의 속성이 존재하지 않는 경우

는 없음 반환되지 않습니다.

제 질문은 요소에있는 모든 속성 목록을 얻으려면 어떻게합니까? get_attributes() 또는 get_attribute_names() 메소드가없는 것 같습니다.

답변

36

그것은 셀레늄 webdriver API를 사용하여 가능하지,하지만 당신은 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) 

데모 :

>>> 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'} 
완성도를 위해서

, 대체 솔루션가 될 것이다 태그의 outerHTML을 가져 와서 HTML 구문 분석기를 사용하여 속성을 구문 분석하십시오. 예 (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

이는 W3C 사양에 포함되지 않은 이유 어떤 생각? 근시안적인 것으로 보인다. http://www.w3.org/TR/webdriver/#get-element-attribute – raven

+0

@raven 잘 모르겠다. 널리 사용되지 않을 수도있다. 훨씬 더 자주 사용자는 하나의 속성을 원할 것입니다. 좋은 질문입니다. 감사합니다. – alecxe

+1

대체 : lxml element.attrib는 모든 속성을 가진 멋진 사용 가능한 사전을 반환합니다. – Sandeep

3

다음은 모든 속성의 목록을 가져옵니다과 나를 위해 값을 (때로는 문자열로 변환)의 PhantomJS 또는 크롬 드라이버 이상 사용 :

elem.get_property('attributes')[0] 

로를 그냥 이름을 얻으십시오 :

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

여기에 답변을 시도하고 있습니다. Google 홈페이지의 검색 창에서만 테스트 해 보았습니다. @ alecxe의 대답을 위의 'outerHTML'에 대해 사용했습니다. html을 얻은 후 속성 이름과 일치하는 정규식 ([a-z]+-?[a-z]+_?)='?"?을 사용했습니다. 정규 표현식은 점점 더 많은 경우와 일치하도록 수정되어야한다고 생각합니다. 그러나 우리가 필요로하는 필수적인 이름은 "무엇이 등호 뒤에 있는지"입니다.

는 아래 코드에 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) 

테스트를 감안할 때

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) 

출력 :