我试图在索引的帮助下找到元素。
目前我在xpath
下方使用提供匹配的索引值来识别
//table/tbody/tr[@index='1']
如何找到具有最大索引值的元素?
答案 0 :(得分:3)
您可以使用内置的max
函数,将key
参数指定为检索index
属性的函数。
# Setup
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://example.com')
rows = browser.find_elements_by_xpath("//table/tbody/tr")
# Solution
max_element = max(rows, key=lambda e: e.get_attribute('index'))
如果lambda
看起来有点混乱,你可以把它分解成一个简单的函数:
def get_index(element): return element.get_attribute('index')
max_element = max(rows, key=get_index)
如果您需要多个最大值,我会在每个上面调用get_attribute
并将其传递给max
以获得最大值index
,然后再次遍历列表以获得最大值:
max_index = max(e.get_attribute('index') for e in rows)
max_elements = [e for e in rows if e.get_attribute('index') == max_index]
答案 1 :(得分:0)
你可以尝试这样的事情。我不认为有一个xpath可以直接找到最高值。
trs = driver.find_elements_by_xpath("//table/tbody/tr")
max = 0
i = 0
for index, tr in enumerate(trs):
if max < int(tr.get_attribute('index')):
max = int(tr.get_attribute('index'))
i = index
max = trs[i]
# If there are more than one elements with the same max value
maxs = driver.find_elements_by_xpath("//table/tbody/tr[@index='" + str(max) + "']")
答案 2 :(得分:0)
Below code worked for me:
trs = driver.find_elements_by_xpath("//table/tbody/tr")
max = 0
i = 1
for tr in trs:
if max < int(tr.get_attribute('index')):
max = int(tr.get_attribute('index'))
i = max
print (str(i))