如何通过 Selenium 和 Python 使用 classname 属性定位最后一个 Web 元素

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

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

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 based on the value of the classname attribute you can use either of the following 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"))