Selenium:driver.find_elements_by_xpath()和driver.find_elements_by_class_name()之间的区别

2024-10-02 14:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题:

tag = driver.find_elements_by_xpath('//*[@class="du4w35lb k4urcfbm l9j0dhe7 sjgh65i0"]')
tag = driver.find_elements_by_class_name("du4w35lb k4urcfbm l9j0dhe7 sjgh65i0")

我原以为两者的工作原理相同,但当我运行它们时,第一个返回一些元素,而第二个返回一个空列表


Tags: name元素列表bytagdriverelementsfind
1条回答
网友
1楼 · 发布于 2024-10-02 14:18:18

按类名(类名)查找元素

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

You can find a relevant detailed discussion in Invalid selector: Compound class names not permitted error using Selenium


通过xpath(xpath)

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

相关问题 更多 >