How to locate the last web element using classname attribute through Selenium and Python

若如初见. 提交于 2021-02-05 08:47:05

问题


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]

回答1:


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:

  • Using XPATH, find_element* and last():

    print(driver.find_element_by_xpath("//*[@class='_3ko75'][last()]").get_attribute("title"))
    
  • Using XPATH, find_elements* and [-1]:

    print(driver.find_elements_by_xpath("//*[@class='_3ko75']")[-1].get_attribute("title"))
    

Preferably using WebDriverWait:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='_3ko75'][last()]"))).get_attribute("title"))

or

print(WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='_3ko75']")))[-1].get_attribute("title"))


来源:https://stackoverflow.com/questions/62957266/how-to-locate-the-last-web-element-using-classname-attribute-through-selenium-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!