【问题标题】:How to locate the last web element using classname attribute through Selenium and Python如何通过 Selenium 和 Python 使用 classname 属性定位最后一个 Web 元素
【发布时间】:2020-11-07 10:54:24
【问题描述】:
getphone = driver.find_element_by_class_name('_3ko75')[-1]
phone = getphone.get_attribute("title")

不工作我需要获取字符串格式的标题。

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]

【问题讨论】:

  • @andrea 仍然无法正常工作:getphone = driver.find_element_by_class_name('_3ko75')[-1] phone = getphone.get_attribute("title")
  • 我只是编辑了您的问题,以便更好地组织代码。我没有提供任何答案
  • 谢谢安德烈
  • find_element 只返回一个 WebElement 对象。为什么最后使用 [-1]?

标签: python selenium selenium-webdriver xpath getattribute


【解决方案1】:

根据您的代码试验,要根据 classname 属性的值获取最后一个 WebElement 的标题,您可以使用以下任一 Locator Strategies

  • 使用XPATHfind_element*last()

    print(driver.find_element_by_xpath("//*[@class='_3ko75'][last()]").get_attribute("title"))
    
  • 使用XPATHfind_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"))

【讨论】:

  • @VictorMaihato 很高兴能为您提供帮助。 Upvote 答案如果这个/任何答案对您/对您有帮助,以造福未来的读者。
最近更新 更多