DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead

网友投稿 512 2022-08-23


DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead

DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead driver.find_element_by_####("###")

弃用警告:find_element_by_* 的一系列命令已经被弃用。请使用 find_element() 代替......

一、解决方式

1、首先需要导入By包

from selenium.webdriver.common.by import By

2、用 find_element() 代替 find_element_by_* [例举部分常用的]

driver = webdriver.Chrome("chromedriver.exe")# driver.find_element_by_name("NAME")driver.find_element(By.NAME, "NAME")# driver.find_element_by_class_name("CLASS_NAME")driver.find_element(By.CLASS_NAME, "CLASS_NAME")# driver.find_element_by_id("ID")driver.find_element(By.ID, "ID")# driver.find_element_by_xpath("XPATH")driver.find_element(By.XPATH, "XPATH")

二、分析源码

以 find_element_by_name()为例

1、find_element_by_name() 源码如下:

selenium.webdriver.remote.webdriver.WebDriver.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)

当进入find_element_by_name()方法,首先会提示弃用警告,最后返回的内容还是调用find_element() 方法,对应传入查找方式By.NAME

2、find_element() 源码如下

selenium.webdriver.remote.webdriver.WebDriver.find_element

def find_element(self, by=By.ID, value=None) -> WebElement: """ Find an element given a By strategy and locator. :Usage: :: element = driver.find_element(By.ID, 'foo') :rtype: WebElement """ if isinstance(by, RelativeBy): return self.find_elements(by=by, value=value)[0] if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENT, { 'using': by, 'value': value})['value']

isinstance() 函数来判断一个对象是否是一个已知的类型,如果是则返回并跳转到 find_elements() 方法执行, 如果不是则接着进入判断,看by 的内容和哪个匹配,给by和value赋对应的值,最后返回调用execute()执行结果

3、by.py 源码

selenium.webdriver.common.by.By

class By(object): """ Set of supported locator strategies. """ ID = "id" XPATH = "xpath" LINK_TEXT = "link text" PARTIAL_LINK_TEXT = "partial link text" NAME = "name" TAG_NAME = "tag name" CLASS_NAME = "class name" CSS_SELECTOR = "css selector"


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spring retry方法调用失败重试机制示例解析
下一篇:07 Python matplotlib numpy 动态爱心唯一的ta(0713男团)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~