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 相关文章推荐
Python smallseg分词用法实例分析
May 28 Python
深入浅析python定时杀进程
Jun 06 Python
Python实现统计代码行的方法分析
Jul 12 Python
python中 chr unichr ord函数的实例详解
Aug 06 Python
Python探索之实现一个简单的HTTP服务器
Oct 28 Python
解决Pycharm中import时无法识别自己写的程序方法
May 18 Python
利用 Flask 动态展示 Pyecharts 图表数据方法小结
Sep 04 Python
Python简易计算器制作方法代码详解
Oct 31 Python
Python爬虫HTPP请求方法有哪些
Jun 03 Python
Python通过format函数格式化显示值
Oct 17 Python
关于Python错误重试方法总结
Jan 03 Python
Python通过loop.run_in_executor执行同步代码 同步变为异步
Apr 11 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
Base64在线编码解码实现代码 演示与下载
2011/01/08 PHP
php 去除html标记--strip_tags与htmlspecialchars的区别详解
2013/06/26 PHP
php获取mysql字段名称和其它信息的例子
2014/04/14 PHP
php操作xml入门之cdata区段
2015/01/23 PHP
Javascript中的Split使用方法与技巧
2007/03/09 Javascript
Some tips of wmi scripting in jscript (1)
2007/04/03 Javascript
Javascript学习笔记8 用JSON做原型
2010/01/11 Javascript
利用jq让你的div居中的好方法分享
2013/11/21 Javascript
jQuery中Form相关知识汇总
2015/01/06 Javascript
jQuery实现返回顶部功能
2016/02/23 Javascript
怎样判断jQuery当前元素是隐藏还是显示
2016/11/23 Javascript
vue + socket.io实现一个简易聊天室示例代码
2017/03/06 Javascript
Vue.js 插件开发详解
2017/03/29 Javascript
详解webpack打包vue时提取css
2017/05/26 Javascript
JavaScript基于activexobject连接远程数据库SQL Server 2014的方法
2017/07/12 Javascript
JavaScript定义函数的三种实现方法
2017/09/23 Javascript
javascript实现电脑和手机版样式切换
2017/11/10 Javascript
vue、react等单页面项目部署到服务器的方法及vue和react的区别
2018/09/29 Javascript
js实现弹幕飞机效果
2020/08/27 Javascript
[46:20]DOTA2-DPC中国联赛 正赛 PSG.LGD vs LBZS BO3 第二场 1月22日
2021/03/11 DOTA
python通过pil模块将raw图片转换成png图片的方法
2015/03/16 Python
详解Python中find()方法的使用
2015/05/18 Python
python实现简单购物商城
2016/05/21 Python
Python的Tornado框架实现异步非阻塞访问数据库的示例
2016/06/30 Python
python 读取竖线分隔符的文本方法
2018/12/20 Python
python print出共轭复数的方法详解
2019/06/25 Python
基于Pycharm加载多个项目过程图解
2020/01/19 Python
Python实现代码块儿折叠
2020/04/15 Python
python gui开发——制作抖音无水印视频下载工具(附源码)
2021/02/07 Python
台湾菁英交友:结识黄金单身的台湾人
2018/01/22 全球购物
武汉世纪畅想数字传播有限公司 .NET笔试题
2015/06/13 面试题
教师考核材料
2014/05/21 职场文书
党的群众路线调研报告
2014/11/03 职场文书
给老婆的检讨书1000字
2015/01/01 职场文书
公司庆典欢迎词
2015/01/26 职场文书
刘公岛导游词
2015/02/05 职场文书