【问题标题】:Seleneium Python shows DeprecationWarnings with driver.find_element_by_xpath()Selenium Python 使用 driver.find_element_by_xpath() 显示弃用警告
【发布时间】:2022-01-24 20:39:44
【问题描述】:

好的,所以我正在使用笔记本电脑 rn,我从我的 PC 复制并粘贴了我的代码,但它突然无法正常工作。我已经安装了相同的 Selenium,但现在它正在运行,我收到了 DeprecationWarnings,driver.find_element_by_xpath 不起作用等等。

def click():
    driver = webdriver.Chrome(executable_path="C:\webdrivers\chromedriver.exe", chrome_options=options_)
    driver.get("http://www.discord.com")
    driver.find_element_by_xpath()

这是我写的不再起作用的例子,driver.find_element_by_xpath() 有一条线穿过它!当我在另一个 py 文件(在 pycharm 中)中重写它时,它不喜欢我使用驱动程序,它带有红色下划线。

有人能解释一下到底发生了什么吗?

【问题讨论】:

    标签: python selenium deprecation-warning findelement selenium-webdriver-python


    【解决方案1】:

    现在你需要使用这个:

    from selenium import webdriver
    from selenium.webdriver.common.by import By  
    
    def click():
        driver = webdriver.Chrome(executable_path="C:\webdrivers\chromedriver.exe", 
        chrome_options=options_)
        driver.get("http://www.discord.com")
        driver.find_element(By.XPATH, 'your xpath')
    

    这适用于 By.CLASS_NAME、By.CSS_SELECTOR 等

    【讨论】:

      【解决方案2】:

      此错误消息...

       DeprecationWarning: find_element_by_* commands are deprecated
      

      ...暗示 find_element_by_* 命令现在与最新的 Selenium Python 库中的 DeprecationWarning 相关联。


      此更改与 Selenium 4 Release Candidate 1 changelog 内联,其中提到:

      指定“find_element_by_* ...”警告是弃用警告 (#9700)


      兼容代码

      您必须使用 find_element() 而不是 find_element_by_*。一个例子:

      • 使用xpath

        driver.find_element_by_xpath("element_xpath")
        

        需要替换为:

        driver.find_element(By.XPATH, "element_xpath")
        

      您需要添加以下导入:

      from selenium.webdriver.common.by import By
      

      此外,您必须使用 options 而不是 chrome_options,因为 chrome_options 现在已弃用。

      您可以在以下位置找到一些相关的详细讨论:


      解决方案

      实际上,您的代码块将是:

      def click():
          driver = webdriver.Chrome(executable_path="C:\webdrivers\chromedriver.exe", options=options_)
          driver.get("http://www.discord.com")
          driver.find_element(By.XPATH, "element_xpath")
      

      【讨论】:

        猜你喜欢
        • 2021-02-19
        • 2017-08-22
        • 2020-03-25
        • 2016-09-30
        • 1970-01-01
        • 2018-07-15
        相关资源
        最近更新 更多