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模拟登录12306的方法
Dec 30 Python
Python导出DBF文件到Excel的方法
Jul 25 Python
利用python实现命令行有道词典的方法示例
Jan 31 Python
python3中bytes和string之间的互相转换
Feb 09 Python
使用Python开发SQLite代理服务器的方法
Dec 07 Python
django写用户登录判定并跳转制定页面的实例
Aug 21 Python
Python实现图片批量加入水印代码实例
Nov 30 Python
python实现快递价格查询系统
Mar 03 Python
Python列表切片常用操作实例解析
Mar 10 Python
python实现TCP文件传输
Mar 20 Python
PHP基于phpqrcode类库生成二维码过程解析
May 28 Python
Python request post上传文件常见要点
Nov 20 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
一个PHP+MSSQL分页的例子
2006/10/09 PHP
解析PHP中ob_start()函数的用法
2013/06/24 PHP
PHP命名空间用法实例分析
2019/09/04 PHP
用javascript自动显示最后更新时间
2007/03/15 Javascript
JavaScript弹簧振子超简洁版 完全符合能量守恒,胡克定理
2009/10/25 Javascript
Javascript 刷新全集常用代码
2009/11/22 Javascript
jQuery之浮动窗口实现代码(两种方法)
2010/09/08 Javascript
使用js实现数据格式化
2014/12/03 Javascript
js中的事件捕捉模型与冒泡模型实例分析
2015/01/10 Javascript
js仿黑客帝国字母掉落效果代码分享
2020/11/08 Javascript
解决jquery插件:TypeError:$.browser is undefined报错的方法
2015/11/21 Javascript
实例剖析AngularJS框架中数据的双向绑定运用
2016/03/04 Javascript
JS密码生成与强度检测完整实例(附demo源码下载)
2016/04/06 Javascript
限制文本框只能输入数字||只能是数字和小数点||只能是整数和浮点数
2016/05/27 Javascript
基于AngularJs + Bootstrap + AngularStrap相结合实现省市区联动代码
2016/05/30 Javascript
Js中async/await的执行顺序详解
2017/09/22 Javascript
小程序tab页无法传递参数的方法
2018/08/03 Javascript
工作中常用到的ES6语法
2018/09/04 Javascript
Node.js爬虫如何获取天气和每日问候详解
2019/08/26 Javascript
python 随机数生成的代码的详细分析
2011/05/15 Python
使用python实现ANN
2017/12/20 Python
Windows下anaconda安装第三方包的方法小结(tensorflow、gensim为例)
2018/04/05 Python
关于keras中keras.layers.merge的用法说明
2020/05/23 Python
详解html5页面 rem 布局适配方法
2018/01/12 HTML / CSS
新加坡航空官方网站:Singapore Airlines
2016/10/13 全球购物
德国最大的设计师鞋网上商店:Budapester
2017/12/07 全球购物
英国露营设备和户外服装购物网站:Simply Hike
2019/05/05 全球购物
JYSK加拿大:购买家具、床垫、家居装饰等
2020/02/14 全球购物
婚庆公司的创业计划书
2014/01/22 职场文书
会计电算化大学生职业规划书
2014/02/05 职场文书
运动会稿件200字
2014/02/07 职场文书
服装设计师职业生涯规划范文
2014/02/28 职场文书
妇女干部培训方案
2014/05/12 职场文书
第一批党的群众路线教育实践活动总结报告
2014/07/03 职场文书
大学生党员自我批评思想汇报
2014/10/10 职场文书
农村党支部承诺书
2015/04/30 职场文书