그것은 셀레늄 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'}
이는 W3C 사양에 포함되지 않은 이유 어떤 생각? 근시안적인 것으로 보인다. http://www.w3.org/TR/webdriver/#get-element-attribute – raven
@raven 잘 모르겠다. 널리 사용되지 않을 수도있다. 훨씬 더 자주 사용자는 하나의 속성을 원할 것입니다. 좋은 질문입니다. 감사합니다. – alecxe
대체 : lxml element.attrib는 모든 속성을 가진 멋진 사용 가능한 사전을 반환합니다. – Sandeep