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数据结构树和二叉树简介
Apr 29 Python
python实现在windows服务中新建进程的方法
Jun 30 Python
Python获取邮件地址的方法
Jul 10 Python
Python有序字典简单实现方法示例
Sep 28 Python
基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解
Oct 13 Python
Python线性回归实战分析
Feb 01 Python
Python中%是什么意思?python中百分号如何使用?
Mar 20 Python
在python中pandas读文件,有中文字符的方法
Dec 12 Python
python实现KNN分类算法
Oct 16 Python
使用python动态生成波形曲线的实现
Dec 04 Python
python读取mysql数据绘制条形图
Mar 25 Python
Python字典实现伪切片功能
Oct 28 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
2006/12/23 PHP
php 记录进行累加并显示总时长为秒的结果
2011/11/04 PHP
smarty内置函数config_load用法实例
2015/01/22 PHP
php根据命令行参数生成配置文件详解
2019/03/15 PHP
PHP基于session.upload_progress 实现文件上传进度显示功能详解
2019/08/09 PHP
“不能执行已释放的Script代码”错误的原因及解决办法
2007/09/09 Javascript
jQuery的学习步骤
2011/02/23 Javascript
关闭浏览器窗口弹出提示框并且可以控制其失效
2014/04/15 Javascript
jquery实现的鼠标拖动排序Li或Table
2014/05/04 Javascript
浅析JavaScript基本类型与引用类型
2014/05/28 Javascript
JavaScript前补零操作实例
2015/03/11 Javascript
ES6新特性:使用export和import实现模块化详解
2017/07/31 Javascript
JS中数组实现代码(倒序遍历数组,数组连接字符串)
2019/12/29 Javascript
vue项目接口域名动态获取操作
2020/08/13 Javascript
[01:48]帕吉至宝加入游戏,遗迹战场现“千劫神屠”
2018/04/07 DOTA
python使用itchat实现手机控制电脑
2018/02/22 Python
python 读取txt中每行数据,并且保存到excel中的实例
2018/04/29 Python
Python3中正则模块re.compile、re.match及re.search函数用法详解
2018/06/11 Python
python实现简易数码时钟
2021/02/19 Python
Django web框架使用url path name详解
2019/04/29 Python
python多项式拟合之np.polyfit 和 np.polyld详解
2020/02/18 Python
python GUI模拟实现计算器
2020/06/22 Python
Python使用pyexecjs代码案例解析
2020/07/13 Python
纯CSS3编写的的精美动画进度条(无flash/无图像/无脚本/附源码)
2013/01/07 HTML / CSS
一款超酷的js+css3实现的3D标签云特效兼容ie7/8/9
2013/11/18 HTML / CSS
StudentUniverse英国:学生航班、酒店和旅游
2019/08/25 全球购物
Made in Design英国:设计家具、照明、家庭装饰和花园家具
2019/09/24 全球购物
个人实用的自我评价范文
2013/11/23 职场文书
群众路线教育实践活动心得体会
2014/03/07 职场文书
精彩广告词大全
2014/03/19 职场文书
2014年乡镇党建工作总结
2014/11/11 职场文书
教师工作决心书
2015/02/04 职场文书
保密法制宣传月活动总结
2015/05/07 职场文书
MySQL 分页查询的优化技巧
2021/05/12 MySQL
简单总结SpringMVC拦截器的使用方法
2021/06/28 Java/Android
游戏《我的世界》澄清Xbox版暂无计划加入光追
2022/04/03 其他游戏