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采集博客中上传的QQ截图文件
Jul 18 Python
Python建立Map写Excel表实例解析
Jan 17 Python
python面试题Python2.x和Python3.x的区别
May 28 Python
python 列表输出重复值以及对应的角标方法
Jun 11 Python
详解DeBug Python神级工具PySnooper
Jul 03 Python
使用Matplotlib 绘制精美的数学图形例子
Dec 13 Python
python  ceiling divide 除法向上取整(或小数向上取整)的实例
Dec 27 Python
详解Python 实现 ZeroMQ 的三种基本工作模式
Mar 24 Python
解决tensorflow/keras时出现数组维度不匹配问题
Jun 29 Python
python中的split、rsplit、splitlines用法说明
Oct 23 Python
Python还能这么玩之只用30行代码从excel提取个人值班表
Jun 05 Python
如何在Python中妥善使用进度条详解
Apr 05 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
PHP3 safe_mode 失效漏洞
2006/10/09 PHP
为你总结一些php系统类函数
2015/10/21 PHP
PHP 构造函数和析构函数原理与用法分析
2020/04/21 PHP
setTimeout和setInterval的浏览器兼容性分析
2007/02/27 Javascript
javascript基础知识大集锦(二) 推荐收藏
2011/01/13 Javascript
javascript学习笔记(三) String 字符串类型介绍
2012/06/19 Javascript
判断一个对象是否为jquery对象的方法
2014/03/12 Javascript
利用函数的惰性载入提高javascript代码执行效率
2014/05/05 Javascript
js鼠标悬浮出现遮罩层的方法
2015/01/28 Javascript
JavaScript中英文字符长度统计方法示例【按照中文占2个字符】
2017/01/17 Javascript
纯js三维数组实现三级联动效果
2017/02/07 Javascript
详解angularjs中的隔离作用域理解以及绑定策略
2017/05/31 Javascript
阿里大于短信验证码node koa2的实现代码(最新)
2017/09/07 Javascript
jQuery实现打开网页自动弹出遮罩层或点击弹出遮罩层功能示例
2017/10/19 jQuery
vue+element的表格实现批量删除功能示例代码
2018/08/17 Javascript
JavaScript canvas实现雪花随机动态飘落
2020/02/08 Javascript
Vue CLI3移动端适配(px2rem或postcss-plugin-px2rem)
2020/04/27 Javascript
Python同时向控制台和文件输出日志logging的方法
2015/05/26 Python
Python实现获取命令行输出结果的方法
2017/06/10 Python
如何表示python中的相对路径
2020/07/08 Python
Python配置pip国内镜像源的实现
2020/08/20 Python
html5 canvas fillRect坐标和大小的问题解决方法
2014/03/26 HTML / CSS
UGG雪地靴荷兰官网:UGG荷兰
2016/09/09 全球购物
美国购买和销售礼品卡平台:Raise
2017/01/13 全球购物
蔻驰西班牙官网:COACH西班牙
2019/01/16 全球购物
Koral官方网站:女性时尚运动服
2019/04/10 全球购物
建筑学推荐信
2013/11/03 职场文书
致接力运动员广播稿
2014/02/17 职场文书
教学改革实施方案
2014/03/31 职场文书
小学班干部竞选演讲稿
2014/04/24 职场文书
2014年九一八事变演讲稿
2014/09/14 职场文书
“四风”问题对照检查材料思想汇报
2014/09/16 职场文书
2014年银行年终工作总结
2014/12/19 职场文书
工作感想范文
2015/08/07 职场文书
2016机关干部作风建设心得体会
2016/01/21 职场文书
教你怎么用Python实现GIF动图的提取及合成
2021/06/15 Python