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脚本
Feb 10 Python
python实现linux下使用xcopy的方法
Jun 28 Python
Python Socket实现简单TCP Server/client功能示例
Aug 05 Python
利用Python循环(包括while&for)各种打印九九乘法表的实例
Nov 06 Python
python并发编程之线程实例解析
Dec 27 Python
通过Py2exe将自己的python程序打包成.exe/.app的方法
May 26 Python
python爬虫自动创建文件夹的功能
Aug 01 Python
Python 单元测试(unittest)的使用小结
Nov 14 Python
Django 接收Post请求数据,并保存到数据库的实现方法
Jul 12 Python
python实现大文本文件分割
Jul 22 Python
Python学习之os模块及用法
Jun 03 Python
python 算法题——快乐数的多种解法
May 27 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实现ODBC数据分页显示一例
2006/10/09 PHP
php中curl和file_get_content的区别
2014/05/10 PHP
教你如何在CI框架中使用 .htaccess 隐藏url中index.php
2014/06/09 PHP
浅析php原型模式
2014/11/25 PHP
PHP中__autoload和Smarty冲突的简单解决方法
2016/04/08 PHP
PHP模板引擎Smarty中变量的使用方法示例
2016/04/11 PHP
PHP 应用容器化以及部署方法
2018/02/12 PHP
PHP APP微信提现接口代码
2018/09/30 PHP
Packer 3.0 JS压缩及混淆工具 下载
2007/05/03 Javascript
javascript 放大镜效果js组件 qsoft.PopBigImage.v0.35 加入了chrome支持
2009/04/07 Javascript
javascript中的array数组使用技巧
2010/01/31 Javascript
详谈JavaScript内存泄漏
2014/11/14 Javascript
jQuery将所有被选中的checkbox某个属性值连接成字符串的方法
2015/01/24 Javascript
JavaScript使用指针操作实现约瑟夫问题实例
2015/04/07 Javascript
Bootstrap使用基础教程详解
2016/09/05 Javascript
web前端开发upload上传头像js示例代码
2016/10/22 Javascript
微信公众号开发 自定义菜单跳转页面并获取用户信息实例详解
2016/12/08 Javascript
js前端实现图片懒加载(lazyload)的两种方式
2017/04/24 Javascript
基于javascript 显式转换与隐式转换(详解)
2017/12/15 Javascript
微信小程序实现滚动消息通知
2018/02/02 Javascript
Vue 通过自定义指令回顾v-内置指令(小结)
2018/09/03 Javascript
vue axios请求频繁时取消上一次请求的方法
2018/11/10 Javascript
详解Node.js amqplib 连接 Rabbit MQ最佳实践
2019/01/24 Javascript
使用vue实现多规格选择实例(SKU)
2019/08/23 Javascript
python&MongoDB爬取图书馆借阅记录
2016/02/05 Python
python爬虫_实现校园网自动重连脚本的教程
2018/04/22 Python
把django中admin后台界面的英文修改为中文显示的方法
2019/07/26 Python
pytorch 实现在预训练模型的 input上增减通道
2020/01/06 Python
将python文件打包exe独立运行程序方法详解
2020/02/12 Python
修复iPhone的safari浏览器上submit按钮圆角bug
2012/12/24 HTML / CSS
详解window.open被浏览器拦截的解决方案
2019/07/18 HTML / CSS
护士自我评价范文
2014/01/25 职场文书
2014年四风问题个人对照自查剖析材料
2014/09/15 职场文书
2016年领导干部廉政承诺书
2016/03/24 职场文书
在前女友婚礼上,用Python破解了现场的WIFI还把名称改成了
2021/05/28 Python
Java 超详细讲解数据结构中的堆的应用
2022/04/02 Java/Android