python selenium禁止加載某些請求

python selenium webdriver請求時間過長, 屏蔽無用請求

問題描述

通過selenium請求目標網站時候, 真實數據(我這裏是驗證碼圖片)已經加載出來, 由於網站做了第三方上報所以得等待很久, 但是上報這個請求不是必須的.

例如
驗證碼已經加載完成, 但是huatuo.qq.com響應時間過長 , webdriver.get()的機制是等待請求的url響應全部完成才進行下一步. 顯示等待和隱式等待的作用是每隔多少秒來檢測一下這個地址是否加載完成, 所以此處不生效.
那我要做的是: 當請求目標url時候, 希望webdriver不上報或者屏蔽huatuo.qq.com…這樣就能節省大量時間, 從而進行下一步操作
在這裏插入圖片描述

解決方案

  1. 在通過selenium打開目標url後, 植入js插件, 通過插件來屏蔽上報url
  2. 配置selenium屬性, 添加屏蔽規則
    chrome_options.add_argument('--host-resolver-rules=MAP report.huatuo.qq.com 127.0.0.1')

最終效果

在這裏插入圖片描述
這樣就能專注於目標url, 更快的執行下一步.

其他屬性配置

  1. options.add_argument(‘headless’) # 無頭模式
  2. options.add_argument(‘window-size={}x{}’.format(width, height)) # 直接配置大小和set_window_size一樣
  3. options.add_argument(‘disable-gpu’) # 禁用GPU加速
  4. options.add_argument(‘proxy-server={}’.format(self.proxy_server)) # 配置代理
  5. options.add_argument(’–no-sandbox’) # 沙盒模式運行
  6. options.add_argument(’–disable-setuid-sandbox’) # 禁用沙盒
  7. options.add_argument(’–disable-dev-shm-usage’) # 大量渲染時候寫入/tmp而非/dev/shm
  8. options.add_argument(’–user-data-dir={profile_path}’.format(profile_path)) # 用戶數據存入指定文件
  9. options.add_argument('no-default-browser-check) # 不做瀏覽器默認檢查
  10. options.add_argument("–disable-popup-blocking") # 允許彈窗
  11. options.add_argument("–disable-extensions") # 禁用擴展
  12. options.add_argument("–ignore-certificate-errors") # 忽略不信任證書
  13. options.add_argument("–no-first-run") # 初始化時爲空白頁面
  14. options.add_argument(’–start-maximized’) # 最大化啓動
  15. options.add_argument(’–disable-notifications’) # 禁用通知警告
  16. options.add_argument(’–enable-automation’) # 通知(通知用戶其瀏覽器正由自動化測試控制)
  17. options.add_argument(’–disable-xss-auditor’) # 禁止xss防護
  18. options.add_argument(’–disable-web-security’) # 關閉安全策略
  19. options.add_argument(’–allow-running-insecure-content’) # 允許運行不安全的內容
  20. options.add_argument(’–disable-webgl’) # 禁用webgl
  21. options.add_argument(’–homedir={}’) # 指定主目錄存放位置
  22. options.add_argument(’–disk-cache-dir={臨時文件目錄}’) # 指定臨時文件目錄
  23. options.add_argument(‘disable-cache’) # 禁用緩存
  24. options.add_argument(‘excludeSwitches’, [‘enable-automation’]) # 開發者模式

參考

其他詳細配置 請點擊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章