【问题标题】:How can I count the number of attributes of an element in Selenium Python?如何计算 Selenium Python 中元素的属性数?
【发布时间】:2013-03-20 15:24:21
【问题描述】:

具有以下 HTML 代码:

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

对于 XPAth 可访问的对象:

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

如何在不知道其名称的情况下通过 Selenium WebDriver + Python 2.7 计算其属性(class, id)?

我期待像 count = 2 这样的东西。

【问题讨论】:

    标签: python-2.7 selenium-webdriver


    【解决方案1】:

    知道了!这应该适用于 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.

    附:这可以进一步增强,例如将空格与 或 / 一起剥离。

    【讨论】:

      【解决方案2】:

      这并不容易。

      每个元素都有一系列隐含的属性以及明确定义的属性(例如选择、禁用等)。因此,我能想到的唯一方法是获取对父级的引用,然后使用 JavaScript 执行器获取 innerHTML:

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

      然后,您必须解析 innerHTML 返回的内容以提取单个元素,然后一旦您隔离了您感兴趣的元素,您将不得不再次解析该元素以提取属性列表。

      【讨论】:

      • 如果我这样做:elem = driver.find_element_by_xpath(xpath) print elem.get_attribute("outerHTML") print elem.get_attribute("innerHTML") 我得到:&lt;span class="warning"&gt;WARNING:&lt;/span&gt;WARNING: 那么,也许一些 Python REGEX 结合 elem.get_attribute("outerHTML") 可能会成功?跨度>
      • 好点,我没想过使用outerHTML(这是有道理的,因为它会给你当前选择的元素,DOH)。
      猜你喜欢
      • 2016-03-24
      • 2015-03-03
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2021-03-23
      • 2013-09-21
      • 1970-01-01
      相关资源
      最近更新 更多