如何通过 Selenium 和 Python 使用 classname 属性定位最后一个 web 元素 [英] How to locate the last web element using classname attribute through Selenium and Python
本文介绍了如何通过 Selenium 和 Python 使用 classname 属性定位最后一个 web 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
getphone = driver.find_element_by_class_name('_3ko75')[-1]
phone = getphone.get_attribute("title")
不工作,我需要获取字符串格式的标题.
Not working I need to get the title on string format.
Exception has occurred: TypeError
'WebElement' object is not subscriptable
File "C:\Users\vmaiha\Documents\Python Projects\Project 01\WP_Answer.py", line 43, in check
getphone = driver.find_element_by_class_name('_3ko75')[-1]
推荐答案
根据你的代码试用,得到最后的标题 WebElement 基于 classname 属性的值,您可以使用以下任一定位器策略:
Based on your code trials, to get the title of the last WebElement based on the value of the classname attribute you can use either of the following Locator Strategies:
使用
XPATH
、find_element*
和last()
:
print(driver.find_element_by_xpath("//*[@class='_3ko75'][last()]").get_attribute("title"))
使用 XPATH
、find_elements*
和 [-1]
:
print(driver.find_elements_by_xpath("//*[@class='_3ko75']")[-1].get_attribute("title"))
最好使用 WebDriverWait:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='_3ko75'][last()]"))).get_attribute("title"))
或
print(WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='_3ko75']")))[-1].get_attribute("title"))
这篇关于如何通过 Selenium 和 Python 使用 classname 属性定位最后一个 web 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文