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开发常用的一些开源Package分享
Feb 14 Python
python基于BeautifulSoup实现抓取网页指定内容的方法
Jul 09 Python
Python实现的堆排序算法原理与用法实例分析
Nov 22 Python
Python实现按特定格式对文件进行读写的方法示例
Nov 30 Python
Python类的继承和多态代码详解
Dec 27 Python
python实现图像识别功能
Jan 29 Python
python2 与 pyhton3的输入语句写法小结
Sep 10 Python
Python 输出时去掉列表元组外面的方括号与圆括号的方法
Dec 24 Python
python读取文件名并改名字的实例
Jan 07 Python
python 获取毫秒数,计算调用时长的方法
Feb 20 Python
python学习将数据写入文件并保存方法
Jun 07 Python
python数字图像处理:图像简单滤波
Jun 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正则表达式替换站点关键字链接后空白的解决方法
2014/09/16 PHP
php+mysqli批量查询多张表数据的方法
2015/01/29 PHP
基于PHP实现假装商品限时抢购繁忙的效果
2015/10/16 PHP
在次封装easyui-Dialog插件实现代码
2010/11/14 Javascript
JS继承 笔记
2011/07/13 Javascript
红米手机抢购的js代码
2014/03/10 Javascript
js判断手机浏览器操作系统和微信浏览器的方法
2016/04/30 Javascript
jQuery的each循环用法简单示例
2016/06/12 Javascript
Bootstrap的class样式小结
2016/12/01 Javascript
js微信支付实现代码
2016/12/22 Javascript
jquery 正整数数字校验正则表达式
2017/01/10 Javascript
node.js到底要不要加分号浅析
2018/07/11 Javascript
Vue请求JSON Server服务器数据的实现方法
2018/11/02 Javascript
详解vue 不同环境配置不同的打包命令
2019/04/07 Javascript
vue 的 solt 子组件过滤过程解析
2019/09/07 Javascript
VUE项目中加载已保存的笔记实例方法
2019/09/14 Javascript
Vue router传递参数并解决刷新页面参数丢失问题
2020/12/02 Vue.js
[12:36]《DOTA2》国服注册与激活指南全攻略
2013/04/28 DOTA
Python实现的金山快盘的签到程序
2013/01/17 Python
在Django的模型中添加自定义方法的示例
2015/07/21 Python
一键搞定python连接mysql驱动有关问题(windows版本)
2016/04/23 Python
python中redis的安装和使用
2016/12/04 Python
Python爬虫利用cookie实现模拟登陆实例详解
2017/01/12 Python
python爬取指定微信公众号文章
2018/12/20 Python
jupyter notebook 添加kernel permission denied的操作
2020/04/21 Python
CSS3打造百度贴吧的3D翻牌效果示例
2017/01/04 HTML / CSS
KIEHL’S科颜氏官方旗舰店:源自美国的顶级护肤品牌
2018/06/07 全球购物
俄罗斯护发和专业化妆品购物网站:Hihair
2019/09/28 全球购物
介绍一下gcc特性
2012/01/20 面试题
opencv实现图像平移效果
2021/03/24 Python
乡镇精神文明建设汇报材料
2014/08/15 职场文书
政风行风建设整改方案
2014/10/27 职场文书
2014年度工作总结报告
2014/12/15 职场文书
美术教师个人总结
2015/02/06 职场文书
资料员岗位职责范本
2015/04/13 职场文书
辛德勒的名单观后感
2015/06/03 职场文书