Search code examples
pythonseleniumselenium-webdriverxpathgetattribute

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


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]

Solution

  • 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"))