Reputation: 15
Examples:
# 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')
Basically, I want to know:
1 - Are there differences between the two? If there are, what are they?
2 - Generally speaking, are there differences between these?
find_element_by_class_name(el): find_element(By.CLASS_NAME, el);
find_element_by_name(el): find_element(By.NAME, el)
3 - Why is a DeprecationWarning
shown when the first method is executed?
Upvotes: 1
Views: 1489
Reputation: 387
They are the same, the find_element_by_name
call find_element
method and pass By.NAME
to by
arguments.
This is the source code:
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)
All the find_element_by_*
methods are call find_element
method with different by
arguments.
You should go to see selenium webdriver
class sourcecode for detail.
This is selenium official api doc. https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/webdriver/remote/webdriver.html#WebDriver
Upvotes: 1
Reputation: 193108
As @GuiHva also mentioned, there is no difference between the two lines:
driver.find_element_by_name('q')
and
driver.find_element(By.NAME, 'q')
as in the current release of selenium4 Python client find_element_by_name(name)
under the hood still invokes:
self.find_element(by=By.NAME, value=name)
but along with a DeprecationWarning.
The current implementation of find_element_by_name() is as follows:
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)
As @AutomatedTester
mentions:
The decision was to simplify the APIs across the languages and this does that.
Upvotes: 1