我有个问题:
tag = driver.find_elements_by_xpath('//*[@class="du4w35lb k4urcfbm l9j0dhe7 sjgh65i0"]')
tag = driver.find_elements_by_class_name("du4w35lb k4urcfbm l9j0dhe7 sjgh65i0")
我认为两者的工作方式相同,但是当我运行它们时,第一个返回了一些元素,而第二个返回了一个空列表。
我有个问题:
tag = driver.find_elements_by_xpath('//*[@class="du4w35lb k4urcfbm l9j0dhe7 sjgh65i0"]')
tag = driver.find_elements_by_class_name("du4w35lb k4urcfbm l9j0dhe7 sjgh65i0")
我认为两者的工作方式相同,但是当我运行它们时,第一个返回了一些元素,而第二个返回了一个空列表。
find_elements_by_class_name(class_name)按类名查找元素并返回一个包含元素的列表(如果找到的话)。如果没有,则为空列表。它被定义为:
def find_elements_by_class_name(self, name):
"""
Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_class_name('foo')
"""
warnings.warn("find_elements_by_* commands are deprecated. Please use find_elements() instead")
return self.find_elements(by=By.CLASS_NAME, value=name)
值得注意的是,find_elements_by_class_name()
接受单个类作为参数。传递多个类,您将面临以下错误:
Message: invalid selector: Compound class names not permitted
一个例子:
tags = driver.find_elements(By.CLASS_NAME, "du4w35lb")
您可以在Invalid selector: Compound class names not allowed error using Selenium中找到相关的详细讨论
find_elements_by_xpath(xpath)通过 xpath 查找多个元素并返回一个包含元素的列表(如果找到的话)。如果没有,则为空列表。它被定义为:
def find_elements_by_xpath(self, xpath):
"""
Finds multiple elements by xpath.
:Args:
- xpath - The xpath locator of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")
"""
warnings.warn("find_elements_by_* commands are deprecated. Please use find_elements() instead")
return self.find_elements(by=By.XPATH, value=xpath)
一个例子:
tags = driver.find_elements(By.XPATH, "//*[@class='du4w35lb k4urcfbm l9j0dhe7 sjgh65i0']")