selenium设置浏览器为headless无头模式(Chrome和Firefox)


Posted in Python onJanuary 08, 2021

新版本的selenium已经明确警告将不支持PhantomJS,建议使用headless的Chrome或FireFox。

两者使用方式非常类似,基本步骤为:

  • 下载驱动
  • 创建选项,设定headless
  • 创建WebDriver,指定驱动位置和选项
  • 对URL发起请求,获得结果,进行解析

Chrome

驱动的下载路径为:https://chromedriver.storage.googleapis.com/index.html

接下来创建选项并设定headless:

options = webdriver.ChromeOptions()
options.set_headless()

创建WebDriver,指定驱动位置和选项:

driver = webdriver.Chrome(
  'D://chromedriver_win32//chromedriver', chrome_options=options)

发起请求,获得结果并进行解析:

driver.get('http://www.sohu.com/')
time.sleep(3)
print(driver.page_source)
driver.close()

Firefox

驱动的下载路径为:https://github.com/mozilla/geckodriver

启动的步骤与Chrome一致,只不过使用的选项对象和创建的WebDriver对象略有不同。直接上源代码:

options = webdriver.FirefoxOptions()
options.set_headless()
driver = webdriver.Firefox(
  firefox_options=options,
  executable_path='D:/geckodriver-win64/geckodriver')
driver.get('http://www.sohu.com/')
time.sleep(3)
print(driver.page_source)
driver.close()

 SELENIUM使用HEADLESS无头模式实现无界面运行

先导包:

from selenium.webdriver.chrome.options import Options

加入如下配置:

chrome_options = Options()

chrome_options.add_argument('--window-size=1920,1080')   # 设置窗口界面大小

chrome_options.add_argument('--headless')

driver = webdriver.Chrome(chrome_options=chrome_options)

参考代码:

from selenium import webdriver
import time
import multiprocessing
from selenium.webdriver.chrome.options import Options



class Zutuan():
  def __init__(self):
    """打开浏览器"""
    self.chrome_options = Options()
    self.chrome_options.add_argument('--window-size=1920,1080')
    self.chrome_options.add_argument('--headless')
    self.driver = webdriver.Chrome(chrome_options=self.chrome_options)

  def open_zutuan(self, url):
    """传入组团url"""
    self.driver.get(url)
    #self.driver.maximize_window()
    self.driver.refresh()
    #time.sleep(0.01)
    self.driver.implicitly_wait(30)    # todo implicitly隐式等待,等待元素可见

  def option_element(self, user, password):
    """xpath定位元素"""
    self.driver.find_element_by_xpath('//div[@class="login a"]/i').click()
    time.sleep(0.01)
    self.driver.find_element_by_xpath('//div[@class="a-title"]').click()
    self.driver.find_element_by_xpath('//input[@type="text" or @class="userName"]').send_keys(user)
    self.driver.find_element_by_xpath('//input[@type="password"]').send_keys(password)
    self.driver.find_element_by_xpath('//div[@class="button"]').click()
    time.sleep(1)
    self.driver.refresh()


  def select_commodity(self, content):
    """搜索组团商品"""
    # TODO self.content实例属性传给下面的方法使用,如果想把值给下面的方法用,添加实例属性解决
    self.content = content
    self.driver.find_element_by_xpath('//input[@type="text"]').send_keys(content)
    self.driver.find_element_by_xpath('//div[@class="search"]').click()
    self.driver.refresh()
    #return content

  def result(self):
    """判断搜索商品成功后的提示信息,断言页面是否成功"""
    if self.content in self.driver.page_source:
      #print(self.content)
      print('商品搜索成功,测试通过')
    else:
      print('商品搜索错误,测试失败')

  def closed(self):
    """关闭浏览器"""
    time.sleep(1)
    self.driver.quit()


def run1():
  # TODO 根据操作顺序,调用方法执行
  zt = Zutuan()
  zt.open_zutuan('http://www.zutuan.cn/index.html#/')
  zt.option_element('1489088761@qq.com', 'mg123456')
  zt.select_commodity('香蕉')
  zt.result()
  zt.closed()


class View_details(Zutuan):
  """把商品添加为明星单品,"""
  def check_commodity(self, number):
    """进入商品详情页,点击添加明星单品"""
    self.driver.find_element_by_xpath('//a[@target="_blank"]/img').click()
    self.driver.switch_to.window(self.driver.window_handles[1])
    self.driver.find_element_by_xpath('//div[@class="child start"]').click()
    self.driver.find_element_by_xpath('//div[@class="el-dialog__body"]//input[@type="text"]').send_keys(number)
    self.driver.find_element_by_xpath('//button[@type="button" and @class="el-button el-button--danger"]').click()
    time.sleep(1)

  def result(self):
    """重写父类方法,判断商品添加成功后的提示信息,断言页面是否成功"""
    if '添加成功' in self.driver.page_source:
      print('商品添加成功,测试通过')
    else:
      print('商品添加失败,测试失败')
    # 调用父类方法关闭
    super().closed()


def run2():
  vd = View_details()
  vd.open_zutuan('http://www.zutuan.cn/index.html#/')
  vd.option_element('1489088761@qq.com', 'mg123456')
  vd.select_commodity('苹果')
  vd.check_commodity(91628)
  vd.result()


def main():
  p1 = multiprocessing.Process(target=run1)
  p2 = multiprocessing.Process(target=run2)

  p1.start()
  p2.start()


if __name__ == '__main__':
  main()

到此这篇关于selenium设置浏览器为headless无头模式(Chrome和Firefox)的文章就介绍到这了,更多相关selenium 浏览器为headless无头模式内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
将Django使用的数据库从MySQL迁移到PostgreSQL的教程
Apr 11 Python
Python的Django中django-userena组件的简单使用教程
May 30 Python
Python缩进和冒号详解
Jun 01 Python
Python使用cookielib模块操作cookie的实例教程
Jul 12 Python
python 禁止函数修改列表的实现方法
Aug 03 Python
python爬取网易云音乐评论
Nov 16 Python
详解如何管理多个Python版本和虚拟环境
May 10 Python
Django ORM多对多查询方法(自定义第三张表&ManyToManyField)
Aug 09 Python
python英语单词测试小程序代码实例
Sep 09 Python
Python动态导入模块:__import__、importlib、动态导入的使用场景实例分析
Mar 30 Python
python多进程 主进程和子进程间共享和不共享全局变量实例
Apr 25 Python
python用Configobj模块读取配置文件
Sep 26 Python
python画图时设置分辨率和画布大小的实现(plt.figure())
Jan 08 #Python
python使用matplotlib的savefig保存时图片保存不完整的问题
Jan 08 #Python
Numpy中的数组搜索中np.where方法详细介绍
Jan 08 #Python
python 窃取摄像头照片的实现示例
Jan 08 #Python
详解python使用金山词霸的翻译功能(调试工具断点的使用)
Jan 07 #Python
Opencv+Python识别PCB板图片的步骤
Jan 07 #Python
Django使用django-simple-captcha做验证码的实现示例
Jan 07 #Python
You might like
杏林同学录(五)
2006/10/09 PHP
php有道翻译api调用方法实例
2014/12/22 PHP
一个简单安全的PHP验证码类、PHP验证码
2016/09/24 PHP
php微信公众平台示例代码分析(二)
2016/12/06 PHP
JavaScript 页面坐标相关知识整理
2010/01/09 Javascript
修复ie8&chrome下window的resize事件多次执行
2011/10/20 Javascript
node.js正则表达式获取网页中所有链接的代码实例
2014/06/03 Javascript
Jquery左右滑动插件之实现超级炫酷动画效果附源码下载
2015/12/02 Javascript
Backbone.js框架中简单的View视图编写学习笔记
2016/02/14 Javascript
微信小程序 教程之wxapp视图容器 scroll-view
2016/10/19 Javascript
node.js版本管理工具n无效的原理和解决方法
2016/11/24 Javascript
详解JS数据类型的值拷贝函数(深拷贝)
2017/07/13 Javascript
JavaScript数组去重的多种方法(四种)
2017/09/19 Javascript
基于js文件加载优化(详解)
2018/01/03 Javascript
jQuery实现的监听导航滚动置顶状态功能示例
2018/07/23 jQuery
在Angular中使用JWT认证方法示例
2018/09/10 Javascript
小程序组件之仿微信通讯录的实现代码
2018/09/12 Javascript
小程序如何获取多个formId实现详解
2019/09/20 Javascript
[03:23]我的刀塔你不可能这么可爱 第一期金萌萌的故事
2014/06/20 DOTA
[42:39]老党炸弹人试玩视频
2014/09/03 DOTA
[00:35]2016完美“圣”典风云人物:冷冷宣传片
2016/12/08 DOTA
python计算书页码的统计数字问题实例
2014/09/26 Python
python中__call__方法示例分析
2014/10/11 Python
Python 实现 贪吃蛇大作战 代码分享
2016/09/07 Python
使用Python写一个贪吃蛇游戏实例代码
2017/08/21 Python
Python批量发送post请求的实现代码
2018/05/05 Python
详解PyCharm+QTDesigner+PyUIC使用教程
2019/06/13 Python
Python selenium 自动化脚本打包成一个exe文件(推荐)
2020/01/14 Python
如何在django中运行scrapy框架
2020/04/22 Python
中华在我心中演讲稿
2014/09/13 职场文书
交通事故和解协议书
2014/09/25 职场文书
辞职信格式范文
2015/05/13 职场文书
城南旧事读书笔记
2015/06/29 职场文书
Vue中插槽slot的使用方法与应用场景详析
2021/06/08 Vue.js
Lombok的详细使用及优缺点总结
2021/07/15 Java/Android
SpringBoot 整合mongoDB并自定义连接池的示例代码
2022/02/28 MongoDB