selenium连接已打开的Firefox浏览器

这篇具有很好参考价值的文章主要介绍了selenium连接已打开的Firefox浏览器。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

原理:将session_idurl进行记录,下次打开firefox浏览器进行复用

import os,pickle,json,win32api
from selenium import webdriver
from selenium.webdriver import Remote
from selenium.webdriver.chrome import options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.remote.webdriver import WebDriver as remoteWebdriver
from pathlib import Path

import logging as log
log.basicConfig(level=log.INFO)

command_executor_key = "command_executor"
session_id_key = "session_id"


class ReuseBrowser(Remote):
    def __init__(self, command_executor, session_id):
        self.r_session_id = session_id
        Remote.__init__(self, command_executor=command_executor, desired_capabilities={})

    def start_session(self, capabilities, browser_profile=None):
        """
        启用已有session_id
        start_session方法重写(去除selenium库Remote类每次实例化都会调用start_session这个方法新建一个会话)
        """
        if not isinstance(capabilities, dict):
            raise InvalidArgumentException("Capabilities must be a dictionary")
        if browser_profile:
            if "moz:firefoxOptions" in capabilities:
                capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded
            else:
                capabilities.update({'firefox_profile': browser_profile.encoded})

        self.capabilities = options.Options().to_capabilities()
        self.session_id = self.r_session_id
        self.w3c = False

def get_firefox_info_path():
    """获得firefox信息存储路径"""
    temp_path = os.getenv('TEMP')
    log.info("temp path:%s" % temp_path)
    selenium_path = Path(temp_path).joinpath("selenium")
    if not selenium_path.exists():
        selenium_path.mkdir(parents=True, exist_ok=True)
    return str(selenium_path.joinpath("selenium_firefox_info.json").resolve())

def close_firefox():
    """
    关闭firefox浏览器
    @return:
    """
    os.system("TASKKILL /F /IM firefox.exe /T")
    os.system("TASKKILL /F /IM geckodriver.exe /T")

def start_geckodriver(driver_path):
    """打开geckodriver驱动"""
    log.info("start driver_path:%s" % driver_path)
    win32api.ShellExecute(0,"open",driver_path,None,None,0)

class Firefox():
    def __init__(self,firefox_path, driver_path,command_executor=None,option=None,capabilities=None):
        self.firefox_path = firefox_path
        self.driver_path = driver_path
        if not command_executor:
            command_executor = "127.0.0.1:4444"
        self.command_executor = command_executor
        if not capabilities:
            capabilities = DesiredCapabilities.FIREFOX
        self.capabilities = capabilities
        if not option:
            self.option = webdriver.FirefoxOptions()
        if self.firefox_path:
            self.option.binary = firefox_path
        #firefox信息存储路径
        self.get_firefox_info_path = get_firefox_info_path()
    
    def start_firefox(self):
        #关闭firefox浏览器和驱动
        close_firefox()
        #重新开启驱动
        start_geckodriver(self.driver_path)
        driver = remoteWebdriver(command_executor=self.command_executor,
                                                      desired_capabilities=self.capabilities,
                                                      options=self.option
                                                      ) 
        #写入
        firefox_info = {}
        firefox_info[session_id_key] = driver.session_id
        firefox_info[command_executor_key] = driver.command_executor._url
        log.info("session_id:%s" % driver.session_id)
        log.info("url:%s" % driver.command_executor._url)
        with open(self.get_firefox_info_path,"w") as write_f:
            json.dump(firefox_info,write_f,indent=4,ensure_ascii=False)
        self.driver = driver

    def resume(self):
        #获得firefox信息存储路径
        info_path = Path(self.get_firefox_info_path)
        if info_path.exists():
            # 路径存在
            # 读取信息
            with open(str(info_path),"r") as load_file:
                try:
                    load_dict = json.load(load_file)
                    session_id = load_dict[session_id_key]
                    command_executor = load_dict[command_executor_key]
                    log.info("...load info...")
                    log.info("session_id:%s" % session_id)
                    log.info("command_executor:%s" % command_executor)
                    self.driver = ReuseBrowser(command_executor,session_id)
                    self.driver.refresh()
                except:
                    log.info("存储信息有误,重新打开FireFox")
                    self.start_firefox()
        else:
            #路径不存在
            self.start_firefox()

调用文章来源地址https://www.toymoban.com/news/detail-518361.html

if __name__ == "__main__":
    firefox_path = r"C:\Program Files\Mozilla Firefox\firefox.exe"
    driver_path = r"D:\gitee\selenium_template\cw_rpa\driver\geckodriver.exe"
    firefox = Firefox(firefox_path, driver_path)
    firefox.resume()
    driver = firefox.driver
    driver.get("http://www.baidu.com")

到了这里,关于selenium连接已打开的Firefox浏览器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python用selenium打开浏览器后秒关闭浏览器-解决方法

    学习selenium的时候,上手第一个脚本发现成功打开浏览器后,代码执行完毕浏览器又秒关闭了,代码如下: 1、检查代码,代码中没有写driver.quit()或driver.close()方法,也没有其它错误提示; 2、检查版本号,浏览器版本号,驱动版本号,确认版本号没有问题; 3、最后找到解决

    2024年02月11日
    浏览(56)
  • python爬虫进阶篇:Scrapy中使用Selenium+Firefox浏览器爬取沪深A股股票行情

    上篇记录了Scrapy搭配selenium的使用方法,有了基本的了解后我们可以将这项技术落实到实际需求中。目前很多股票网站的行情信息都是动态数据,我们可以用Scrapy+selenium对股票进行实时采集并持久化,再进行数据分析、邮件通知等操作。 详情请看上篇笔记 items middlewares setti

    2024年02月04日
    浏览(42)
  • 解决Python selenium打开浏览器自动退出

    刚学selenium,在网上复制了启动浏览器的代码,结果打开Chrome浏览器跳转网页后,浏览器自动退出了,可是并没有调用quit(),查了下解决方案,说是降版本,不想降,所以找了其他方法: 设置启动参数即可,驱动过程结束后保持浏览器的打开状态: options.add_experimental_option(

    2024年02月05日
    浏览(35)
  • 免费 Selenium各大浏览器驱动【谷歌chrme、火狐Firefox、IE浏览器】

    aardio群 625494397 废话不多说 直接开整! 竟然还有脸收费 服了 下载对应版本的浏览器驱动 目标网址 应用场景 Selenium库涉及到 安装selenium库 下载对应浏览器驱动 找到浏览器对应版本 最后直接上代码

    2024年02月16日
    浏览(41)
  • python通过selenium爬取网页信息,python获取浏览器请求内容,控制已经打开的浏览器

    背景:通过python中直接get或者urlopen打开一些有延迟加载数据的网页,会抓取不到部分信息。 1. 命令行打开chrome,并开启调试端口 (前提,找到chrome安装目录,找到chrome.exe所在路径,添加到环境变量中,例如我的是C:Program FilesGoogleChromeApplication) remote-debugging-port指定远程调试

    2024年02月16日
    浏览(55)
  • selenium 使用已打开的chrome浏览器(python版)

    使用selenium 的 webdriver 调试的时候,每次都是打开一个新的 chrome浏览器实例,特别不方便,那怎么使用上次打开的chrome浏览器实例呢,以下是完整代码,亲测可用 python版本:3.10 系统:win11 步骤1,先写一个打开 chrome浏览器 的文件1,里面指定这个chrome浏览器实例的端口号

    2024年02月14日
    浏览(31)
  • 如何在Firefox火狐浏览器点击链接打开新标签页、搜索、和书签

    打开Firefox火狐浏览器设置 在Firefox的地址栏输入 about:config 按回车键后,打开了一个警告页面,单击“接受风险并继续”即可,如下图所 在新标签页打开网页上的链接(点击链接打开新标签页) 在窗口中输入 browser.urlbar.openintab 双击显示的值更改为 true 在新标签中打开搜索结

    2024年02月05日
    浏览(33)
  • selenium基本使用、无头浏览器(chrome、FireFox)、搜索标签

    这个模块:既能发请求,又能解析,还能执行js selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行 JavaScript代码的问题 selenium 会做web方向的自动化测试 appnium 会做 app方向的自动化测试 selenium 可以操作浏览器,模拟人的 行为 下载浏览器驱动

    2024年02月04日
    浏览(43)
  • 关于python的selenium控制已经打开的edge浏览器

     下载edge驱动后,放在edge的exe文件同目录下,并将exe的目录添加到系统“用户“变量path中。之后在exe目录下打开cmd 。在cmd中输入msedge.exe --remote-debugging-port=9222 --user-data-dir=\\\"D:pythonseleniumEdge\\\"      -----注意:提前建这个文件夹\\\"D:pythonseleniumEdge\\\" 

    2024年02月07日
    浏览(36)
  • Selenium | 控制已打开的浏览器-python-edge

    诡异的验证码和微信扫码登录着实让爬虫难堪,那是否可以在已经打开的浏览器基础上,继续运行自动化脚本?通过手工登录后,再让脚本执行程序,这样可以解决很大的一个痛点。 右键点击桌面上的“Edge浏览器”,点击“属性”。 复制“ 起始位置 ”路径。 插句话:点击“

    2024年02月03日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包