Python中多瀏覽器實(shí)例項(xiàng)目的隔離策略與實(shí)現(xiàn)
在 Python 實(shí)現(xiàn)多瀏覽器實(shí)例的 JavaScript 注入時(shí),要確保 數(shù)據(jù)隔離、會話隔離、存儲隔離,否則多個(gè)實(shí)例之間可能會共享 Cookie、LocalStorage 或者其他持久化數(shù)據(jù),導(dǎo)致數(shù)據(jù)污染或沖突。以下是一些關(guān)鍵的隔離策略和代碼實(shí)現(xiàn)。
1. 數(shù)據(jù)隔離
問題:
- 默認(rèn)情況下,不同瀏覽器實(shí)例可能會共享同一個(gè) Profile(如 Chrome 賬戶、緩存等)。
- 共享 LocalStorage 或 SessionStorage 可能導(dǎo)致數(shù)據(jù)沖突。
解決方案:
- 啟動 Chrome 時(shí),使用 --user-data-dir 讓每個(gè)實(shí)例使用獨(dú)立的數(shù)據(jù)目錄。
- 禁用緩存 --disable-cache,避免數(shù)據(jù)復(fù)用。
- 運(yùn)行時(shí)清理 LocalStorage 和 SessionStorage。
代碼示例(Pyppeteer):
import asyncio import os from pyppeteer import launch async def inject_js(browser_id, url, script): user_data_dir = f"./chrome_profiles/profile_{browser_id}" # 每個(gè)實(shí)例獨(dú)立的用戶數(shù)據(jù)目錄 os.makedirs(user_data_dir, exist_ok=True) browser = await launch( headless=False, args=[ '--no-sandbox', '--disable-cache', f'--user-data-dir={user_data_dir}', # 使用獨(dú)立的用戶數(shù)據(jù)目錄 ] ) page = await browser.newPage() await page.goto(url) # 執(zhí)行 JavaScript 代碼并清理本地存儲 await page.evaluate(f""" {script} localStorage.clear(); sessionStorage.clear(); """) print(f"[{browser_id}] 執(zhí)行完畢") await browser.close() async def main(): url = "https://www.example.com" script = "document.body.style.backgroundColor = 'green';" tasks = [inject_js(i, url, script) for i in range(5)] # 5 個(gè)瀏覽器實(shí)例 await asyncio.gather(*tasks) asyncio.run(main())
關(guān)鍵點(diǎn):
- 獨(dú)立 user-data-dir:確保不同實(shí)例的數(shù)據(jù)目錄不同,防止緩存、Cookie、LocalStorage 共享。
- 清除本地存儲:每次執(zhí)行前,清除
localStorage
和sessionStorage
,避免數(shù)據(jù)污染。
2. 會話隔離
問題:
瀏覽器實(shí)例可能會共享 Cookie、SessionStorage,導(dǎo)致數(shù)據(jù)不安全或干擾測試。
解決方案:
- 通過 無痕模式(Incognito Mode) 啟動瀏覽器,每個(gè)實(shí)例都會有獨(dú)立的會話。
- 顯式清除 Cookies,避免會話共享。
代碼示例(Selenium):
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import multiprocessing def inject_js_selenium(browser_id, url, script): print(f"[{browser_id}] 啟動瀏覽器...") chrome_options = Options() chrome_options.add_argument("--incognito") # 無痕模式 chrome_options.add_argument("--disable-cache") chrome_options.add_argument("--disable-application-cache") driver = webdriver.Chrome(service=Service("/path/to/chromedriver"), options=chrome_options) driver.get(url) print(f"[{browser_id}] 注入 JavaScript 代碼...") driver.execute_script(script) # 清除 Cookie,確保會話隔離 driver.delete_all_cookies() print(f"[{browser_id}] 注入完成") driver.quit() if __name__ == "__main__": url = "https://www.example.com" script = "document.body.style.backgroundColor = 'blue';" processes = [] for i in range(5): # 5個(gè)瀏覽器實(shí)例 p = multiprocessing.Process(target=inject_js_selenium, args=(i, url, script)) p.start() processes.append(p) for p in processes: p.join()
關(guān)鍵點(diǎn):
- 使用 --incognito 選項(xiàng):避免不同實(shí)例共享 SessionStorage。
- 清除 Cookie:driver.delete_all_cookies() 確保不會話復(fù)用。
3. 存儲隔離
問題:
- 數(shù)據(jù)存儲可能會發(fā)生共享(如 IndexedDB、LocalStorage)。
- 需要在每個(gè)實(shí)例執(zhí)行前,清除本地存儲和數(shù)據(jù)庫。
解決方案:
通過 JavaScript 代碼 清除 IndexedDB、LocalStorage 和 SessionStorage。
代碼示例(Pyppeteer):
async def clear_storage(page): await page.evaluate(""" indexedDB.databases().then(dbs => { for (let db of dbs) { indexedDB.deleteDatabase(db.name); } }); localStorage.clear(); sessionStorage.clear(); """) print("存儲清理完畢") async def inject_js(browser_id, url, script): browser = await launch(headless=False, args=['--no-sandbox']) page = await browser.newPage() await page.goto(url) # 執(zhí)行 JavaScript 代碼并清理存儲 await clear_storage(page) await page.evaluate(script) print(f"[{browser_id}] 執(zhí)行完畢") await browser.close() async def main(): url = "https://www.example.com" script = "document.body.style.backgroundColor = 'yellow';" tasks = [inject_js(i, url, script) for i in range(5)] await asyncio.gather(*tasks) asyncio.run(main())
關(guān)鍵點(diǎn):
- indexedDB.deleteDatabase():刪除 IndexedDB 以防止數(shù)據(jù)泄漏。
- 清理 localStorage 和 sessionStorage,確保不會話存儲干擾。
4. 進(jìn)程隔離
問題:
- 共享瀏覽器進(jìn)程可能導(dǎo)致線程安全問題或數(shù)據(jù)共享。
- 需要確保每個(gè)實(shí)例運(yùn)行在獨(dú)立進(jìn)程中。
解決方案:
通過 多進(jìn)程 multiprocessing 或 asyncio 任務(wù)并發(fā),確保每個(gè)瀏覽器實(shí)例是獨(dú)立的進(jìn)程。
代碼示例(多進(jìn)程 + Selenium):
import multiprocessing from selenium import webdriver from selenium.webdriver.chrome.options import Options def start_browser(instance_id): options = Options() options.add_argument("--headless") options.add_argument("--incognito") # 開啟無痕模式 options.add_argument(f"--user-data-dir=./chrome_profile_{instance_id}") # 獨(dú)立數(shù)據(jù)目錄 driver = webdriver.Chrome(options=options) driver.get("https://www.example.com") # 注入 JavaScript 代碼 driver.execute_script("document.body.style.backgroundColor = 'pink';") driver.quit() if __name__ == "__main__": num_instances = 5 # 啟動5個(gè)實(shí)例 processes = [] for i in range(num_instances): p = multiprocessing.Process(target=start_browser, args=(i,)) p.start() processes.append(p) for p in processes: p.join()
關(guān)鍵點(diǎn):
- 獨(dú)立 user-data-dir 目錄,避免多個(gè) Selenium 實(shí)例共享數(shù)據(jù)。
- multiprocessing 多進(jìn)程,確保瀏覽器實(shí)例的完全隔離。
總結(jié)
隔離類型 | 方案 | 實(shí)現(xiàn)方式 |
---|---|---|
數(shù)據(jù)隔離 | 獨(dú)立 user-data-dir、清除 LocalStorage | --user-data-dir、localStorage.clear() |
會話隔離 | 開啟 --incognito 無痕模式 | delete_all_cookies() |
存儲隔離 | 清除 IndexedDB、LocalStorage、SessionStorage | indexedDB.deleteDatabase() |
進(jìn)程隔離 | multiprocessing 啟動多個(gè)瀏覽器實(shí)例 | multiprocessing.Process() |
通過 獨(dú)立會話、無痕模式、存儲清理、進(jìn)程隔離,可以確保每個(gè)瀏覽器實(shí)例完全隔離,不會影響其他實(shí)例的數(shù)據(jù)。
以上就是Python中多瀏覽器實(shí)例項(xiàng)目的隔離策略與實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于Python隔離的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
pyqt5 實(shí)現(xiàn)在別的窗口彈出進(jìn)度條
今天小編就為大家分享一篇pyqt5 實(shí)現(xiàn)在別的窗口彈出進(jìn)度條,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06使用keras實(shí)現(xiàn)非線性回歸(兩種加激活函數(shù)的方式)
這篇文章主要介紹了使用keras實(shí)現(xiàn)非線性回歸(兩種加激活函數(shù)的方式),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07Python處理Excel的14個(gè)常用操作總結(jié)
在數(shù)據(jù)處理和分析的領(lǐng)域中,Excel是一種被廣泛使用的工具,然而,通過Python處理Excel,能夠更好地實(shí)現(xiàn)自動化和批量處理,本文為大家整理了14個(gè)Python處理Excel的常用操作,希望對大家有所幫助2023-12-12python+POP3實(shí)現(xiàn)批量下載郵件附件
這篇文章主要為大家詳細(xì)介紹了python+POP3實(shí)現(xiàn)批量下載郵件附件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06TensorFlow實(shí)現(xiàn)RNN循環(huán)神經(jīng)網(wǎng)絡(luò)
這篇文章主要介紹了TensorFlow實(shí)現(xiàn)RNN循環(huán)神經(jīng)網(wǎng)絡(luò),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02使用python構(gòu)建WebSocket客戶端的教程詳解
WebSocket是一種在客戶端和服務(wù)器之間實(shí)現(xiàn)雙向通信的協(xié)議,常用于實(shí)時(shí)聊天、實(shí)時(shí)數(shù)據(jù)更新等場景,Python提供了許多庫來實(shí)現(xiàn) WebSocket客戶端,本教程將介紹如何使用Python構(gòu)建WebSocket客戶端,文中通過代碼示例給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12利用Anaconda完美解決Python 2與python 3的共存問題
Anaconda 是 Python 的一個(gè)發(fā)行版,如果把 Python 比作 Linux,那么 Anancoda 就是 CentOS 或者 Ubuntu,下面這篇文章主要給大家介紹了利用Anaconda完美解決Python 2與python 3共存問題的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒。2017-05-05