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

1

1
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]
Filberte answered 17/7, 2020 at 15:35 Comment(4)
@andrea still not working: getphone = driver.find_element_by_class_name('_3ko75')[-1] phone = getphone.get_attribute("title")Filberte
I only edited your question in order to organize in a better way the code. I did not provide any answerReachmedown
Thank you AndreaFilberte
find_element return only a single WebElement Object. Why do you use [-1] at the end?Hydroelectric
H
0

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"))
Hardtop answered 17/7, 2020 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.