【Python】使用Playwright直连到本地浏览器chrome/edge,使用用户数据进行测试
·
# chrome浏览器连接步骤
import subprocess
from playwright.sync_api import sync_playwright
import time
import os
import signal
# 以下为默认浏览器位置以及管理员 Administrator 身份示例
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
user_data_dir = r"C:\Users\Administrator\AppData\Local\Google\Chrome\User Data"
process = subprocess.Popen([chrome_path, '--remote-debugging-port=9222', '--user-data-dir=' + user_data_dir])
time.sleep(2)
with sync_playwright() as playwright:
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
default_context = browser.contexts[0] if browser.contexts else browser.new_context()
page = default_context.pages[0] if default_context.pages else default_context.new_page()
page.goto("https://blog.csdn.net/sjs240?spm=1010.2135.3001.5343")
page.wait_for_timeout(2000)
browser.close()
os.kill(process.pid, signal.SIGTERM)
# edge浏览器连接步骤
import subprocess
from playwright.sync_api import sync_playwright
import time
import psutil
# edge默认使用用户数据,无需指定加载数据
edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
process = subprocess.Popen([edge_path, '--remote-debugging-port=9222'])
time.sleep(2)
with sync_playwright() as playwright:
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
default_context = browser.contexts[0] if browser.contexts else browser.new_context()
page = default_context.pages[0] if default_context.pages else default_context.new_page()
page.goto("https://blog.csdn.net/sjs240?spm=1010.2135.3001.5343")
page.wait_for_timeout(2000)
browser.close()
for proc in psutil.process_iter(['pid', 'name']):
if 'msedge.exe' in proc.info['name'].lower():
proc.terminate()
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)