gpt4 book ai didi

python-2.7 - 如何计算 Selenium Python 中元素的属性数?

转载 作者:行者123 更新时间:2023-12-04 01:17:52 25 4
gpt4 key购买 nike

具有以下 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 这样的结果。

最佳答案

明白了!这应该适用于 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

希望对您有所帮助。

谢谢,

附言这可以进一步增强,比如用 <、> 或/去除空格。

关于python-2.7 - 如何计算 Selenium Python 中元素的属性数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15527715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com