"find_element_by_name('name')" 和 "find_element(By.NAME, 'name')" 有什么区别?

What is the difference between "find_element_by_name('name')" and "find_element(By.NAME, 'name')"?

示例:

# method 1
from selenium import webdriver

PATH = '...'
driver = webdriver.Chrome(PATH)
driver.get('https://google.com')
driver.find_element_by_name('q').send_keys('test')
# method 2
from selenium import webdriver
from selenium.webdriver.common.by import By

PATH = 'c:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://google.com')
driver.find_element(By.NAME, 'q').send_keys('test')

基本上,我想知道:

1 - 两者之间有区别吗?如果有,它们是什么?

2 - 一般来说,这之间有区别吗?

find_element_by_class_name(el): find_element(By.CLASS_NAME, el); 

find_element_by_name(el): find_element(By.NAME, el)

3 - 为什么执行第一个方法时显示 DeprecationWarning

它们是相同的,find_element_by_name 调用 find_element 方法并将 By.NAME 传递给 by 参数。 这是源代码:

def find_element_by_name(self, name):
    """
    Finds an element by name.

    :Args:
     - name: The name of the element to find.

    :Returns:
     - WebElement - the element if it was found

    :Raises:
     - NoSuchElementException - if the element wasn't found

    :Usage:
        element = driver.find_element_by_name('foo')
    """
    return self.find_element(by=By.NAME, value=name)

所有 find_element_by_* 方法都是使用不同的 by 参数调用 find_element 方法。 你应该去看看 selenium webdriver class 源代码以获得详细信息。

这是 selenium 官方 api 文档。 https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/webdriver/remote/webdriver.html#WebDriver

正如@GuiHva 也提到的,这两行之间没有区别:

driver.find_element_by_name('q')

driver.find_element(By.NAME, 'q')

在当前版本的 Python client find_element_by_name(name) 中,引擎盖下仍然调用:

self.find_element(by=By.NAME, value=name)

但是还有 .

目前find_element_by_name()的执行情况如下:

def find_element_by_name(self, name) -> WebElement:
    """
    Finds an element by name.

    :Args:
     - name: The name of the element to find.

    :Returns:
     - WebElement - the element if it was found

    :Raises:
     - NoSuchElementException - if the element wasn't found

    :Usage:
        ::

            element = driver.find_element_by_name('foo')
    """
    warnings.warn(
        "find_element_by_* commands are deprecated. Please use find_element() instead",
        DeprecationWarning,
        stacklevel=2,
    )
    return self.find_element(by=By.NAME, value=name)

为什么会发生这种变化

作为@AutomatedTester mentions:

The decision was to simplify the APIs across the languages and this does that.