从 Selenium 中具有相同 class 的多个元素获取不同的值以获得 Python?

Get the different value from multiple elements with the same class in Selenium for Python?

我有这样的 HTML 代码:

<span class="class_name">10</span>
<span class="class_name">20</span>
<span class="class_name">32</span>

数字(10、20、32)是可变的,可以是32、56和65。

在 Selenium 中我这样做:

findclass = driver.find_element_by_class_name("class_name")

现在,我的目标是获取数字并将其分配给变量,例如:

var1 = 10
var2 = 20
var3 = 32

谢谢。

使用find_elements_by_class_name。它将 return 具有此 class 名称的所有元素的列表。

findclass = driver.find_elements_by_class_name("class_name")

for i in findclass:

    print(i.text)

要查找列表中的第二个元素,只需使用:print(findclass[1].text).

如果您正在寻找一个特定的值,您可以使用 CSS 选择器或 XPath,您不需要所有元素的列表...

@MosheSlavin 的方向是正确的。但是,要将所有值放入 List 中,您必须为 visibility_of_all_elements_located() 引入 WebDriverWait 并且您可以使用以下任一方法:

  • 使用CLASS_NAME:

    print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "class_name")))])
    
  • 使用CSS_SELECTOR:

    print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "span.class_name")))])
    
  • 使用XPATH:

    print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//span[@class='class_name']")))])
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC