2025年2月14日 星期五 甲辰(龙)年 腊月十四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python Selenium 驱动下载与配置使用(详细流程)

时间:02-28来源:作者:点击数:27

1、安装

  • $ pip install selenium

2、下载浏览器驱动(webdriver

3、使用

  • 代码跑起后,没有写关闭浏览器的代码,运行几秒后,浏览器自动关闭的问题解决
  • 验证浏览器驱动是否正常使用,确保 python 环境正常,selenium 包已经安装。
    • # 导入
    • from selenium import webdriver
    • # 如果需要指定路径,但是路径在新版本中被重构到 Service 函数中了
    • # from selenium.webdriver.chrome.service import Service
    • # 延时器
    • from time import sleep
    • # 1、浏览器驱动路径
    • # win_path = 'chromedriver.exe'
    • # mac_path = 'chromedriver'
    • # 2、直接传入字符串路径报错:DeprecationWarning: executable_path has been deprecated, please pass in a Service object
    • # 原因是这种写法将放弃使用
    • # driver = webdriver.Chrome(mac_path)
    • # 2、需要使用 Service 进行包裹一下【推荐】
    • # options = webdriver.ChromeOptions()
    • # options.add_experimental_option('detach', True) # 不自动关闭浏览器
    • # service = Service(mac_path)
    • # driver = webdriver.Chrome(service=service, options=options)
    • # 创建浏览器驱动对象, 以下为创建不同浏览器驱动对象
    • options = webdriver.ChromeOptions()
    • options.add_experimental_option('detach', True) # 不自动关闭浏览
    • driver = webdriver.Chrome(options=options) # Chrome浏览器
    • # driver = webdriver.Firefox() # Firefox浏览器
    • # driver = webdriver.Edge() # Edge浏览器
    • # driver = webdriver.Ie() # Internet Explorer浏览器
    • # driver = webdriver.Opera() # Opera浏览器
    • # driver = webdriver.PhantomJS() # PhantomJS,无界面浏览器看上面 Chrome handless 文章
    • # 打开指定网址
    • driver.get('https://www.baidu.com')
    • # 休眠5秒
    • sleep(5)
    • # 关闭浏览器驱动对象
    • driver.quit()
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门