当前位置:   article > 正文

Selenium入坑——用代码自动下载浏览器驱动_webdriver.chrome(service=chromeservice(chromedrive

webdriver.chrome(service=chromeservice(chromedrivermanager().install()))

常规操作:比如,下载Google浏览器驱动ChromeDriver

1、打开Google浏览器——查看Chrome浏览器版本

2、去驱动网站下载对应的驱动——网站地址:chrome浏览器驱动

3、安装Chromedriver.exe

4、Selenium启动Chromedriver

     常规操作的限制:代码在不同环境下适配不同的驱动

     有没有更好的办法呢???—— 让代码根据我们的浏览器自动匹配驱动 

优化操作:代码实现浏览器与驱动的适配

      ​​​​​​首先在终端安装webdriver_manager ,如下图所示,前置条件为selenium版本为4.x       

# selenium 为4.x 版本

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
# 自动下载Google浏览器对应的驱动
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

driver.get("https://www.baidu.com/") # 下载完成后打开百度搜索页面
from time import sleep
sleep(20)

为了方便每次使用,可以将其封装起来,然后直接调用:

# 封装

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

class Browser_driver(object):

      def browser_init(self):

            # 自动下载Google浏览器对应的驱动                       

            driver= webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()

            ))

            return driver

# 调用

from  python_learning.config.browser_driver import Browser_driver

# 注释

# 使用时,将python_learning.config.browser_driver替换为Browser_driver的封装路径

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/925998
推荐阅读
相关标签
  

闽ICP备14008679号