<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      【自動(dòng)化】使用PlayWright+代理IP實(shí)現(xiàn)多環(huán)境隔離

      Playwright是由微軟公司2020年初發(fā)布的新一代自動(dòng)化測(cè)試工具,相較于目前最常用的Selenium,它僅用一個(gè)API即可自動(dòng)執(zhí)行Chromium、Firefox、WebKit等主流瀏覽器自動(dòng)化操作。

      對(duì)各種開發(fā)語言也有非常好的支持。常用的NodeJs、Java、python都有支持,且有豐富的文檔參考。

      Python環(huán)境下的安裝使用

      1、安裝依賴庫
      pip install playwright

      2、安裝瀏覽器驅(qū)動(dòng)文件
      安裝好依賴庫之后,會(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)景

      常見的如爬蟲,可能需要使用代理IP隔離開不同的瀏覽器進(jìn)行數(shù)據(jù)抓取。

      像另一些需要多號(hào)操作的營銷內(nèi)容,也需要多個(gè)瀏覽器互相隔離開。更高要求的才會(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、普通的無痕模式,用完即銷毀。這種方式下,瀏覽器的歷史記錄之類的不會(huì)保存。適合用于爬蟲性的工作。

      代碼大致是這樣的。

      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無頭模式,這樣瀏覽器不會(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("http://www.rzrgm.cn/yoyoketang")
      
          page.pause()
      

      3、直連系統(tǒng)的Chrome。如果系統(tǒng)有Chrome瀏覽器,playwright可以直接連接,并進(jìn)行操作。但是需要做一些配置。

      這也是我目前用得最多的模式。

      核心的原理就是使用CDP連接上Chrome。需要開啟Chrome時(shí),指定一個(gè)調(diào)試端口,供我們遠(yuǎn)程連接上去使用。

      官方提供的具體函數(shù)是
      pw.chromium.connect_over_cdp(cdp_url, timeout=0)

      優(yōu)點(diǎn)在于:
      腳本和瀏覽器分離。腳本開不開,瀏覽器都不影響。只是需要自動(dòng)化的時(shí)候,腳本才去工作。

      缺點(diǎn):
      就是配置略麻煩。好在封裝好之后,就是一次的麻煩,后面也會(huì)比較順暢。

      如何封裝屬于自己的快速啟動(dòng)類,python和java都可以,下次再聊。

      下面以Chrome瀏覽器+動(dòng)態(tài)代理為例構(gòu)建多個(gè)不同的環(huán)境

      由于Chrome自帶的proxy 代理功能并不支持帶賬號(hào)密碼的代理方式。
      而我們采購的代理,肯定都是有賬號(hào)密碼的。

      所以核心點(diǎn)是添加一個(gè)插件,配置上代理,能支持http和socks5的代理,并支持賬號(hào)密碼進(jìn)行連接。

      然后再通過python,調(diào)用系統(tǒng)的瀏覽器,產(chǎn)生不同的環(huán)境,使用不同的代理IP。就能達(dá)到目標(biāo)。

      直接上圖
      file

      沒有好用的收費(fèi)代理,本地模擬了一個(gè)HK節(jié)點(diǎn)的代理。

      可以看到4個(gè)瀏覽器的指紋已經(jīng)不一樣了。配合上代理,就是干凈的環(huán)境了。

      核心的邏輯在于啟用不同的DataDir用戶數(shù)據(jù)目錄,加個(gè)獨(dú)立的代理插件來支持http和socks5的代理,

      1、核心1,使用python來快速啟動(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")}"')
      
      # 啟用無痕
      if config.get('incognito'):
          extParam.append('--incognito')
      
      # 無開屏
      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
          插件來源: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類型)
              proxy_port (int): 代理端口號(hào)(int類型)
              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,
          )
      
          # 先寫ZIP
          with zipfile.ZipFile(plugin_file, 'w') as zp:
              zp.writestr("manifest.json", manifest_json)
              zp.writestr("background.js", background_js)
      
          # 再手寫文件過去
          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的多線程。相信開100個(gè)窗口干活,不是什么難事。

      Playwright在下載上傳方面,比以前的Selenium要強(qiáng)很多。還有很多功能,下次再分享。

      關(guān)注我的公眾號(hào):青塬科技,定期分享經(jīng)驗(yàn)文章。

      posted @ 2024-03-04 14:57  青塬科技  閱讀(1276)  評(píng)論(0)    收藏  舉報(bào)
      主站蜘蛛池模板: 石渠县| 国产一精品一av一免费爽爽| 亚洲成人av在线高清| 巨爆乳中文字幕爆乳区| 中文字幕国产精品自拍| 久久婷婷综合色丁香五月| 诱人的老师hd中文字幕| 老子午夜精品888无码不卡| 亚洲日本国产精品一区| 亚洲AV无码秘?蜜桃蘑菇| 一区二区三区无码高清视频| 久久精品久久精品久久精品| 亚洲一区二区三区在线观看精品中文 | 巩义市| 成人精品色一区二区三区| 成人又黄又爽又色的视频| 明光市| 妺妺窝人体色www婷婷| 国产激情无码一区二区APP| 辽宁省| 成人免费xxxxx在线观看| 暖暖 在线 日本 免费 中文| 国产超碰人人爽人人做| 欧美裸体xxxx极品| 丰满岳乱妇久久久| 桃源县| 国产精品午夜福利精品| 亚洲国产精品综合久久20| 免费看欧美全黄成人片| 亚洲精品自拍视频在线看| 亚洲va韩国va欧美va| 日韩精品一区二区在线视| 鲁丝片一区二区三区免费| 欧美白妞大战非洲大炮| 国产仑乱无码内谢| 国产亚洲人成网站在线观看| 人妻少妇精品系列一区二区 | 国产最大成人亚洲精品| 黄瓜视频在线观看| 国产一级精品在线免费看| 一卡2卡三卡4卡免费网站|