国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

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類每次實例化都會調(diào)用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驅(qū)動"""
    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瀏覽器和驅(qū)動
        close_firefox()
        #重新開啟驅(qū)動
        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()

調(diào)用文章來源地址http://www.zghlxwxcb.cn/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瀏覽器的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • python用selenium打開瀏覽器后秒關閉瀏覽器-解決方法

    python用selenium打開瀏覽器后秒關閉瀏覽器-解決方法

    學習selenium的時候,上手第一個腳本發(fā)現(xiàn)成功打開瀏覽器后,代碼執(zhí)行完畢瀏覽器又秒關閉了,代碼如下: 1、檢查代碼,代碼中沒有寫driver.quit()或driver.close()方法,也沒有其它錯誤提示; 2、檢查版本號,瀏覽器版本號,驅(qū)動版本號,確認版本號沒有問題; 3、最后找到解決

    2024年02月11日
    瀏覽(96)
  • python爬蟲進階篇:Scrapy中使用Selenium+Firefox瀏覽器爬取滬深A股股票行情

    上篇記錄了Scrapy搭配selenium的使用方法,有了基本的了解后我們可以將這項技術落實到實際需求中。目前很多股票網(wǎng)站的行情信息都是動態(tài)數(shù)據(jù),我們可以用Scrapy+selenium對股票進行實時采集并持久化,再進行數(shù)據(jù)分析、郵件通知等操作。 詳情請看上篇筆記 items middlewares setti

    2024年02月04日
    瀏覽(29)
  • 解決Python selenium打開瀏覽器自動退出

    剛學selenium,在網(wǎng)上復制了啟動瀏覽器的代碼,結果打開Chrome瀏覽器跳轉(zhuǎn)網(wǎng)頁后,瀏覽器自動退出了,可是并沒有調(diào)用quit(),查了下解決方案,說是降版本,不想降,所以找了其他方法: 設置啟動參數(shù)即可,驅(qū)動過程結束后保持瀏覽器的打開狀態(tài): options.add_experimental_option(

    2024年02月05日
    瀏覽(25)
  • 免費 Selenium各大瀏覽器驅(qū)動【谷歌chrme、火狐Firefox、IE瀏覽器】

    免費 Selenium各大瀏覽器驅(qū)動【谷歌chrme、火狐Firefox、IE瀏覽器】

    aardio群 625494397 廢話不多說 直接開整! 竟然還有臉收費 服了 下載對應版本的瀏覽器驅(qū)動 目標網(wǎng)址 應用場景 Selenium庫涉及到 安裝selenium庫 下載對應瀏覽器驅(qū)動 找到瀏覽器對應版本 最后直接上代碼

    2024年02月16日
    瀏覽(92)
  • python通過selenium爬取網(wǎng)頁信息,python獲取瀏覽器請求內(nèi)容,控制已經(jīng)打開的瀏覽器

    python通過selenium爬取網(wǎng)頁信息,python獲取瀏覽器請求內(nèi)容,控制已經(jīng)打開的瀏覽器

    背景:通過python中直接get或者urlopen打開一些有延遲加載數(shù)據(jù)的網(wǎng)頁,會抓取不到部分信息。 1. 命令行打開chrome,并開啟調(diào)試端口 (前提,找到chrome安裝目錄,找到chrome.exe所在路徑,添加到環(huán)境變量中,例如我的是C:Program FilesGoogleChromeApplication) remote-debugging-port指定遠程調(diào)試

    2024年02月16日
    瀏覽(97)
  • selenium 使用已打開的chrome瀏覽器(python版)

    使用selenium?的 webdriver?調(diào)試的時候,每次都是打開一個新的?chrome瀏覽器實例,特別不方便,那怎么使用上次打開的chrome瀏覽器實例呢,以下是完整代碼,親測可用 python版本:3.10 系統(tǒng):win11 步驟1,先寫一個打開?chrome瀏覽器?的文件1,里面指定這個chrome瀏覽器實例的端口號

    2024年02月14日
    瀏覽(94)
  • 如何在Firefox火狐瀏覽器點擊鏈接打開新標簽頁、搜索、和書簽

    如何在Firefox火狐瀏覽器點擊鏈接打開新標簽頁、搜索、和書簽

    打開Firefox火狐瀏覽器設置 在Firefox的地址欄輸入 about:config 按回車鍵后,打開了一個警告頁面,單擊“接受風險并繼續(xù)”即可,如下圖所 在新標簽頁打開網(wǎng)頁上的鏈接(點擊鏈接打開新標簽頁) 在窗口中輸入 browser.urlbar.openintab 雙擊顯示的值更改為 true 在新標簽中打開搜索結

    2024年02月05日
    瀏覽(39)
  • selenium基本使用、無頭瀏覽器(chrome、FireFox)、搜索標簽

    這個模塊:既能發(fā)請求,又能解析,還能執(zhí)行js selenium最初是一個自動化測試工具,而爬蟲中使用它主要是為了解決requests無法直接執(zhí)行 JavaScript代碼的問題 selenium 會做web方向的自動化測試 appnium 會做 app方向的自動化測試 selenium 可以操作瀏覽器,模擬人的 行為 下載瀏覽器驅(qū)動

    2024年02月04日
    瀏覽(109)
  • 關于python的selenium控制已經(jīng)打開的edge瀏覽器

    ?下載edge驅(qū)動后,放在edge的exe文件同目錄下,并將exe的目錄添加到系統(tǒng)“用戶“變量path中。之后在exe目錄下打開cmd 。在cmd中輸入msedge.exe --remote-debugging-port=9222 --user-data-dir=\\\"D:pythonseleniumEdge\\\"? ? ? -----注意:提前建這個文件夾\\\"D:pythonseleniumEdge\\\"?

    2024年02月07日
    瀏覽(100)
  • Selenium | 控制已打開的瀏覽器-python-edge

    Selenium | 控制已打開的瀏覽器-python-edge

    詭異的驗證碼和微信掃碼登錄著實讓爬蟲難堪,那是否可以在已經(jīng)打開的瀏覽器基礎上,繼續(xù)運行自動化腳本?通過手工登錄后,再讓腳本執(zhí)行程序,這樣可以解決很大的一個痛點。 右鍵點擊桌面上的“Edge瀏覽器”,點擊“屬性”。 復制“ 起始位置 ”路徑。 插句話:點擊“

    2024年02月03日
    瀏覽(227)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包