selenium/geckodriver 的弃用警告

DeprecationWarning with selenium/geckodriver

DeprecationWarning 是什么意思?

另外,如果我删除“elem”功能,它似乎可以正常工作,但是当 chrome 选项卡打开 link 时,它会立即再次关闭

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyautogui

import unittest
import time


class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(
            executable_path=r'C:\Users\iwanh\Desktop\Geckodriver\geckodriver.exe')

    def test_search_in_python_org_true(self):
        driver = self.driver
        driver.get("https://e-learning.nyc.gr/login/index.php")

        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.clear()
        elem.send_keys("pycon")
        time.sleep(3)
        elem.send_keys(Keys.RETURN)
        self.assertNotIn("No results found.", driver.page_source)

    def test_search_in_python_org_false(self):
        driver = self.driver
        driver.get("http://www.python.org")
        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.clear()
        elem.send_keys("ljueragiuhoerg")
        elem.send_keys(Keys.RETURN)
        time.sleep(2)
        self.assertIn("No results found.", driver.page_source)

    def tearDown(self):
        self.driver.close()


if __name__ == "__main__":
    unittest.main()

代码输出 Output 1 Output 2

使用 selenium4 作为密钥 executable_path 已弃用,您必须使用 Service() class 的实例以及 ChromeDriverManager().install() 命令,如下所示。

Pre-requisites

  • 确保: Selenium 升级到 v4.0.0

解决方案:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.google.com")