Playwright是由微軟公司2020年初發(fā)布的新一代自動(dòng)化測(cè)試工具,相較于目前最常用的Selenium,它僅用一個(gè)API即可自動(dòng)執(zhí)行Chromium、Firefox、WebKit等主流瀏覽器自動(dòng)化操作。
對(duì)各種開(kāi)發(fā)語(yǔ)言也有非常好的支持。常用的NodeJs、Java、python都有支持,且有豐富的文檔參考。
Python環(huán)境下的安裝使用
1、安裝依賴(lài)庫(kù)
pip install playwright
2、安裝瀏覽器驅(qū)動(dòng)文件
安裝好依賴(lài)庫(kù)之后,會(huì)自動(dòng)注冊(cè)全局命令。下面2種方式都可以快速安裝驅(qū)動(dòng)文件(驅(qū)動(dòng)就是內(nèi)置的瀏覽器)
python -m playwright install
或者:
playwright install
如果命令是python3,替換為pip3 install 和python3 -m 即可。
網(wǎng)上有非常多的教程。安裝并非本文的重點(diǎn)。
多環(huán)境隔離的應(yīng)用場(chǎng)景
常見(jiàn)的如爬蟲(chóng),可能需要使用代理IP隔離開(kāi)不同的瀏覽器進(jìn)行數(shù)據(jù)抓取。
像另一些需要多號(hào)操作的營(yíng)銷(xiāo)內(nèi)容,也需要多個(gè)瀏覽器互相隔離開(kāi)。更高要求的才會(huì)使用代理+隔離的方式。
產(chǎn)生完全不一樣的瀏覽器環(huán)境。比如大量的號(hào)去做不同的事。
還有很多常用的場(chǎng)景。獨(dú)立干凈的瀏覽器環(huán)境+Playwright的自動(dòng)化??梢詫?shí)現(xiàn)非常多的有趣的應(yīng)用。
Playwright啟動(dòng)瀏覽器有幾種模式。我們需要先進(jìn)行了解。
1、普通的無(wú)痕模式,用完即銷(xiāo)毀。這種方式下,瀏覽器的歷史記錄之類(lèi)的不會(huì)保存。適合用于爬蟲(chóng)性的工作。
代碼大致是這樣的。
browser = pw.chromium.launch(headless=headless, proxy=my_proxy,
ignore_default_args=ignore_args,
args=default_args)
browserContext = browser.new_context(user_agent=userAgent, storage_state=storage_state)
可以指定UserAgent,這是我們模擬不同操作系統(tǒng)和瀏覽器數(shù)據(jù)的必填項(xiàng)。
也可以指定headless無(wú)頭模式,這樣瀏覽器不會(huì)有界面出現(xiàn)。背后去工作。
2、普通的持久模式,需要指定用戶的數(shù)據(jù)目錄。實(shí)現(xiàn)數(shù)據(jù)的隔離。
比如1號(hào)瀏覽器存到data1,2號(hào)存到data2,數(shù)據(jù)不會(huì)沖突,各干各的事,可以同時(shí)登陸一個(gè)網(wǎng)站的多個(gè)賬號(hào),互不影響。
不方便的地方在于,每次執(zhí)行完任務(wù),瀏覽器會(huì)隨著程序關(guān)閉而關(guān)閉。
copy一段網(wǎng)上的示例
# 獲取 google chrome 的本地緩存文件
USER_DIR_PATH = f"C:\\Users\\{getpass.getuser()}\\AppData\Local\Google\Chrome\\User Data"
with sync_playwright() as p:
browser = p.chromium.launch_persistent_context(
# 指定本機(jī)用戶緩存地址,這是隔離環(huán)境的主要點(diǎn),指定不同的目錄存放用戶的數(shù)據(jù)。
user_data_dir=USER_DIR_PATH,
# 接收下載事件,允許下載需要
accept_downloads=True,
# 設(shè)置 GUI 模式,可以看到瀏覽器界面
headless=False,
bypass_csp=True,
slow_mo=1000,
channel="chrome",
)
page = browser.new_page()
page.goto("https://www.cnblogs.com/yoyoketang")
page.pause()
3、直連系統(tǒng)的Chrome。如果系統(tǒng)有Chrome瀏覽器,playwright可以直接連接,并進(jìn)行操作。但是需要做一些配置。
這也是我目前用得最多的模式。
核心的原理就是使用CDP連接上Chrome。需要開(kāi)啟Chrome時(shí),指定一個(gè)調(diào)試端口,供我們遠(yuǎn)程連接上去使用。
官方提供的具體函數(shù)是
pw.chromium.connect_over_cdp(cdp_url, timeout=0)
優(yōu)點(diǎn)在于:
腳本和瀏覽器分離。腳本開(kāi)不開(kāi),瀏覽器都不影響。只是需要自動(dòng)化的時(shí)候,腳本才去工作。
缺點(diǎn):
就是配置略麻煩。好在封裝好之后,就是一次的麻煩,后面也會(huì)比較順暢。
如何封裝屬于自己的快速啟動(dòng)類(lèi),python和java都可以,下次再聊。
下面以Chrome瀏覽器+動(dòng)態(tài)代理為例構(gòu)建多個(gè)不同的環(huán)境
由于Chrome自帶的proxy 代理功能并不支持帶賬號(hào)密碼的代理方式。
而我們采購(gòu)的代理,肯定都是有賬號(hào)密碼的。
所以核心點(diǎn)是添加一個(gè)插件,配置上代理,能支持http和socks5的代理,并支持賬號(hào)密碼進(jìn)行連接。
然后再通過(guò)python,調(diào)用系統(tǒng)的瀏覽器,產(chǎn)生不同的環(huán)境,使用不同的代理IP。就能達(dá)到目標(biāo)。
直接上圖
沒(méi)有好用的收費(fèi)代理,本地模擬了一個(gè)HK節(jié)點(diǎn)的代理。
可以看到4個(gè)瀏覽器的指紋已經(jīng)不一樣了。配合上代理,就是干凈的環(huán)境了。
核心的邏輯在于啟用不同的DataDir用戶數(shù)據(jù)目錄,加個(gè)獨(dú)立的代理插件來(lái)支持http和socks5的代理,
1、核心1,使用python來(lái)快速啟動(dòng)Chrome
if sys.platform.startswith('linux'): # Linux
exe_name = 'chrome'
extParam.append('--no-sandbox')
elif sys.platform.startswith('win'): # Windows
win_path = 'C:\Program Files\Google\Chrome\Application\chrome.exe'
exe_name = win_path if os.path.exists(win_path) else 'chrome.exe'
elif sys.platform.startswith('darwin'): # Mac
exe_name = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
extParam.append('--no-sandbox')
# 啟用UA
if config.get('user_agent'):
extParam.append(fr'--user-agent="{config.get("user_agent")}"')
# 啟用無(wú)痕
if config.get('incognito'):
extParam.append('--incognito')
# 無(wú)開(kāi)屏
if config.get('no_window'):
extParam.append('--no-startup-window')
command = fr'"{exe_name}" --remote-debugging-port={port} --user-data-dir="{data_dir}" --no-sandbox --disable-gpu --disable-software-rasterize --disable-background-networking --disable-background-mode --disable-sync --disable-blink-features=AutomationControlled --disable-client-side-phishing-detection --disable-default-apps --disable-desktop-notifications --disable-hang-monitor --disable-infobars --disable-notifications --disable-plugins-discovery --no-first-run --dns-prefetch-disable --ignore-certificate-errors --allow-running-insecure-content --test-type --origin-trial-disabled-features=WebGPU --no-default-browser-check --no-service-autorun --disable-popup-blocking --password-store=basic --disable-web-security --disable-dev-shm-usage --disable-component-update --disable-features=RendererCodeIntegrity --disable-features=FlashDeprecationWarning,EnablePasswordsAccountStorage {" ".join(extParam)}'
os.popen(command)
還有不少代碼,就不往上面貼了。
2、核心點(diǎn)2,動(dòng)態(tài)加載插件進(jìn)不同的Chrome環(huán)境,各用各的代理。
def create_proxyauth_extension(proxy_host, proxy_port,
proxy_username, proxy_password,
scheme='http', plugin_dir=None):
"""
代理認(rèn)證插件,返回代理插件的地址
Chrome使用帶賬號(hào)密碼的代理IP
插件來(lái)源:https://github.com/henices/Chrome-proxy-helper
參考:https://ask.hellobi.com/blog/cuiqingcai/10307#articleHeader5
https://my.oschina.net/sunboy2050/blog/1858508
https://github.com/aneasystone/selenium-test/blob/master/08-proxy-with-password.py
https://developer.chrome.com/extensions/proxy
args:
proxy_host (str): 你的代理地址或者域名(str類(lèi)型)
proxy_port (int): 代理端口號(hào)(int類(lèi)型)
proxy_username (str):用戶名(字符串)
proxy_password (str): 密碼 (字符串)
kwargs:
scheme (str): 代理方式 默認(rèn)http
plugin_dir (str): 擴(kuò)展的目錄路徑
return str -> plugin_path
"""
# 插件目錄
if not plugin_dir:
plugin_dir = os.path.join(get_data_dir('chrome_plugin'), f'custom_proxyauth_plugin')
if not os.path.exists(plugin_dir):
os.makedirs(plugin_dir)
# 生成的Zip文件地址
plugin_file = os.path.join(plugin_dir, f"proxy_plugin_{proxy_host}_{proxy_port}.zip")
# 舊文件清理掉
if os.path.exists(plugin_file):
os.remove(plugin_file)
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = string.Template(
"""
var config = {
mode: "fixed_servers",
pacScript: {},
rules: {
singleProxy: {
scheme: "${scheme}",
host: "${host}",
port: ${port}
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "${username}",
password: "${password}"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
"""
).substitute(
host=proxy_host,
port=proxy_port,
username=proxy_username,
password=proxy_password,
scheme=scheme,
)
# 先寫(xiě)ZIP
with zipfile.ZipFile(plugin_file, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
# 再手寫(xiě)文件過(guò)去
with open(os.path.join(plugin_dir, 'manifest.json'), 'w+') as fi:
fi.write(manifest_json)
with open(os.path.join(plugin_dir, 'background.js'), 'w+') as fi:
fi.write(background_js)
return plugin_file
Java也可以用同樣的方式實(shí)現(xiàn)。后續(xù)配上Java的多線程。相信開(kāi)100個(gè)窗口干活,不是什么難事。
Playwright在下載上傳方面,比以前的Selenium要強(qiáng)很多。還有很多功能,下次再分享。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-837877.html
關(guān)注我的公眾號(hào):青塬科技,定期分享經(jīng)驗(yàn)文章。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-837877.html
到了這里,關(guān)于【自動(dòng)化】使用PlayWright+代理IP實(shí)現(xiàn)多環(huán)境隔離的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!