使用 Webdriver 时出现 DepricationWarning

DepricationWarning when using Webdriver

当我 运行 selenium 时,我有时会收到这个 deprication 警告,这真的很奇怪。错误消息不会显示有关警告的大量信息。有修复吗?

错误:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
main.py:15: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  driver.find_element_by_name("gameId").send_keys(gamepin+Keys.ENTER)
main.py:16: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  driver.find_element_by_id("nickname").send_keys(username+Keys.ENTER)
Traceback (most recent call last):
  File "main.py", line 16, in <module>
    driver.find_element_by_id("nickname").send_keys(username+Keys.ENTER)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 472, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="nickname"]"}
  (Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x55f607e05919 <unknown>

使用较新的,因为 driver.find_element_by 已折旧。

driver.find_element(By.ID,"nickname").send_keys(username+Keys.ENTER)

我推荐的是在页面加载之后使用 Webdriver 等待。

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID,"nickname"))).send_keys(username+Keys.ENTER)

导入:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC