2013-03-20 264 views
3

具有以下HTML代碼:如何計算Selenium Python中元素的屬性數量?

<span class="warning" id ="warning">WARNING:</span> 

對於與XPath訪問的對象:

.//*[@id='unlink']/table/tbody/tr[1]/td/span 

怎麼能指望它的屬性(類,ID)由硒的webdriver +的Python 2.7的方式,卻不知道他們的名字?

我在等待類似count = 2的東西。

回答

2

Got it!這應該適用於div,span,img,p和許多其他基本元素。

element = driver.find_element_by_xpath(xpath) #Locate the element. 

outerHTML = element.get_attribute("outerHTML") #Get its HTML 
innerHTML = element.get_attribute("innerHTML") #See where its inner content starts 

if len(innerHTML) > 0: # Let's make this work for input as well 
    innerHTML = innerHTML.strip() # Strip whitespace around inner content 
    toTrim = outerHTML.index(innerHTML) # Get the index of the first part, before the inner content 
    # In case of moste elements, this is what we care about 
    rightString = outerHTML[:toTrim] 
else: 
    # We seem to have something like <input class="bla" name="blabla"> which is good 
    rightString = outerHTML 
# Ie: <span class="something" id="somethingelse"> 

strippedString = rightString.strip() # Remove whitespace, if any 
rightTrimmedString = strippedString.rstrip('<>') # 
leftTrimmedString = rightTrimmedString.lstrip('</>') # Remove the <, >, /, chars. 
rawAttributeArray = leftTrimmedString.split(' ') # Create an array of: 
# [span, id = "something", class="somethingelse"] 

curatedAttributeArray = [] # This is where we put the good values 
iterations = len(rawAttributeArray) 

for x in range(iterations): 
    if "=" in rawAttributeArray[x]: #We want the attribute="..." pairs 
     curatedAttributeArray.append(rawAttributeArray[x]) # and add them to a list 

numberOfAttributes = len(curatedAttributeArray) #Let's see what we got 
print numberOfAttributes # There we go 

我希望這會有所幫助。

感謝, R.

附:這可以進一步增強,例如與<,>或/一起剝離空白。

0

這並不容易。

每個元素都有一系列隱式屬性以及明確定義的屬性(例如選中,禁用等)。因此,我能想到的唯一辦法做到這一點會得到父的引用,然後使用JavaScript執行得到的innerHTML:

document.getElementById('{ID of element}').innerHTML 

那麼你將不得不解析什麼是innerHTML的返回提取出單個元素,然後一旦你隔離了你感興趣的元素,你將再次解析該元素以提取出屬性列表。

+0

如果我做這樣的事情: 'ELEM = driver.find_element_by_xpath(的XPath) 打印elem.get_attribute( 「outerHTML」) 打印elem.get_attribute( 「的innerHTML」)' 我得到: '<警告:'和 '警告:' 因此,也許一些Python REGEX與elem.get_attribute(「outerHTML」)結合可能會有訣竅嗎? – 2013-03-21 07:35:10

+0

好的一點,我沒有想到使用outerHTML(這將有意義,因爲它會給你你當前選擇的元素,DOH)。 – Ardesco 2013-03-21 08:40:44

相關問題