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中使用dict和set方法的教程
Apr 27 Python
python模块之sys模块和序列化模块(实例讲解)
Sep 13 Python
Python排序搜索基本算法之希尔排序实例分析
Dec 09 Python
python变量赋值方法(可变与不可变)
Jan 12 Python
解决PyCharm不运行脚本,而是运行单元测试的问题
Jan 17 Python
python中实现控制小数点位数的方法
Jan 24 Python
使用python实现滑动验证码功能
Aug 05 Python
详解用Pytest+Allure生成漂亮的HTML图形化测试报告
Mar 31 Python
appium+python自动化配置(adk、jdk、node.js)
Nov 17 Python
Python存储读取HDF5文件代码解析
Nov 25 Python
Python使用Opencv打开笔记本电脑摄像头报错解问题及解决
Jun 21 Python
Python 第三方库 openpyxl 的安装过程
Dec 24 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 和 MySQL 基础教程(一)
2006/10/09 PHP
PHP模板引擎smarty详细介绍
2015/05/26 PHP
PHP 计算两个时间段之间交集的天数示例
2019/10/24 PHP
驱动事件的addEvent.js代码
2007/03/27 Javascript
javascript html 静态页面传参数
2009/04/10 Javascript
JavaScript 保存数组到Cookie的代码
2010/04/14 Javascript
基于jQuery的淡入淡出可自动切换的幻灯插件
2010/08/24 Javascript
从零开始学习jQuery (八) 插播:jQuery实施方案
2011/02/23 Javascript
用表格输出1-1000之间的数字实现代码(附特效)
2013/04/21 Javascript
使用正则表达式的格式化与高亮显示json字符串
2014/12/03 Javascript
什么是MEAN?JavaScript编程中的MEAN是什么意思?
2014/12/18 Javascript
使用Chrome浏览器调试AngularJS应用的方法
2015/06/18 Javascript
jQuery实现文本框输入同步的方法
2015/06/20 Javascript
使用jQuery在对象中缓存选择器的简单方法
2015/06/30 Javascript
Jquery实现简单的轮播效果(代码管用)
2016/03/14 Javascript
Bootstrap嵌入jqGrid,使你的table牛逼起来
2016/05/05 Javascript
JavaScript中构造函数与原型链之间的关系详解
2019/02/25 Javascript
phpsir 开发 一个检测百度关键字网站排名的python 程序
2009/09/17 Python
对python append 与浅拷贝的实例讲解
2018/05/04 Python
PyQt 实现使窗口中的元素跟随窗口大小的变化而变化
2019/06/18 Python
python的json中方法及jsonpath模块用法分析
2019/12/06 Python
解决jupyter notebook 出现In[*]的问题
2020/04/13 Python
python列表的逆序遍历实现
2020/04/20 Python
使用sklearn对多分类的每个类别进行指标评价操作
2020/06/11 Python
html5中localStorage本地存储的简单使用
2017/06/16 HTML / CSS
HTML5超文本标记语言的实现方法
2020/09/24 HTML / CSS
大专生工程监理求职信
2013/10/04 职场文书
总经理职责
2013/12/22 职场文书
煤矿机修工岗位职责
2014/02/07 职场文书
建筑结构施工专业推荐信
2014/02/21 职场文书
酒店节能减排方案
2014/05/26 职场文书
放飞理想演讲稿
2014/09/09 职场文书
自查自纠整改报告
2014/11/06 职场文书
党员个人党性分析材料
2014/12/18 职场文书
2019年消防宣传标语集锦
2019/11/21 职场文书
ORM模型框架操作mysql数据库的方法
2021/07/25 MySQL