1. 程式人生 > >一位大神整理的selenium瀏覽器驅動配置

一位大神整理的selenium瀏覽器驅動配置

Selenium Python3 請求頭配置

置頂 2018年08月22日 10:50:43 花小田 閱讀數:707 標籤: Python3 Selenium Chrome 收起

個人分類: Selenium

Selenium官方文件

https://seleniumhq.github.io/selenium/docs/api/py/api.html


谷歌瀏覽器

一、chromeOptions相關配置

chromeOptions 是一個配置 chrome 啟動是屬性的類。通過這個類,我們可以為chrome配置如下引數(這個部分可以通過selenium原始碼看到):

1.設定 chrome 二進位制檔案位置 (binary_location

)
2.新增啟動引數 (add_argument)
3.新增擴充套件應用 (add_extension, add_encoded_extension)
4.新增實驗性質的設定引數 (add_experimental_option)
5.設定偵錯程式地址 (debugger_address)

原始碼剖析:

# .\Lib\site-packages\selenium\webdriver\chrome\options.py
class Options(object):
    def __init__(self):
        self._binary_location = ''           # 設定 chrome 二進位制檔案位置
        self._arguments = []                 # 新增啟動引數
        self._extension_files = []           # 新增擴充套件應用
        self._extensions = []
        self._experimental_options = {}      # 新增實驗性質的設定引數
        self._debugger_address = None        # 設定偵錯程式地址

1.模擬移動裝置

# 通過設定user-agent,用來模擬移動裝置
user_ag='MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; '+
'CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
options.add_argument('user-agent=%s'%user_ag)
#option.add_argument('--user-agent=iphone')

2禁止圖片載入

from selenium import webdriver
options = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
#或者  使用下面的設定, 提升速度
options.add_argument('blink-settings=imagesEnabled=false')

3.新增代理

from selenium import webdriver
# 靜態IP:102.23.1.105:2005
PROXY = "proxy_host:proxy:port"
options = webdriver.ChromeOptions()
desired_capabilities = options.to_capabilities()
desired_capabilities['proxy'] = {
    "httpProxy": PROXY,
    "ftpProxy": PROXY,
    "sslProxy": PROXY,
    "noProxy": None,
    "proxyType": "MANUAL",
    "class": "org.openqa.selenium.Proxy",
    "autodetect": False
}
driver = webdriver.Chrome(desired_capabilities = desired_capabilities)

4.瀏覽器啟動時安裝crx擴充套件

# -*- coding=utf-8 -*-
from selenium import webdriver
option = webdriver.ChromeOptions()
option.add_extension('d:\crx\AdBlock_v2.17.crx')  # 自己下載的crx路徑
driver = webdriver.Chrome(chrome_options=option)
driver.get('http://www.taobao.com/')

5.載入所有Chrome配置

  用Chrome位址列輸入chrome://version/,檢視自己的“個人資料路徑”,然後在瀏覽器啟動時,呼叫這個配置檔案,程式碼如下:
  

#-*- coding=utf-8 -*-
from selenium import webdriver
option = webdriver.ChromeOptions()
p=r'C:\Users\Administrator\AppData\Local\Google\Chrome\User Data'
option.add_argument('--user-data-dir='+p)  # 設定成使用者自己的資料目錄
driver = webdriver.Chrome(chrome_options=option)

6.攜帶Cookie

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.baidu.com")

    通過使用Chrome選項保持所有登入在會話之間持久user-data-dir

7.其他

# -*- coding: utf-8 -*-
from selenium import webdriver
options = webdriver.ChromeOptions()

#谷歌無頭模式
options.add_argument('--headless')
options.add_argument('--disable-gpu')#谷歌文件提到需要加上這個屬性來規避bug

options.add_argument('disable-infobars')#隱藏"Chrome正在受到自動軟體的控制"
options.add_argument('lang=zh_CN.UTF-8')      # 設定中文
options.add_argument('window-size=1920x3000') # 指定瀏覽器解析度
options.add_argument('--hide-scrollbars')     # 隱藏滾動條, 應對一些特殊頁面
options.add_argument('--remote-debugging-port=9222')
options.binary_location = r'/Applications/Chrome' #手動指定使用的瀏覽器位置

# 更換頭部
user_agent = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
    )
options.add_argument('user-agent=%s'%user_agent)

#設定圖片不載入
prefs = {
    'profile.default_content_setting_values': {
        'images': 2
    }
}
options.add_experimental_option('prefs', prefs)
#或者  使用下面的設定, 提升速度
options.add_argument('blink-settings=imagesEnabled=false')


#設定代理
options.add_argument('proxy-server=' +'192.168.0.28:808')

driver = webdriver.Chrome(chrome_options=options)

#設定cookie
driver.delete_all_cookies()# 刪除所有的cookie
driver.add_cookie({'name':'ABC','value':'DEF'})# 攜帶cookie開啟
driver.get_cookies()

# 通過js新開啟一個視窗
driver.execute_script('window.open("https://www.baidu.com");')

二、chrome位址列命令

  about:version - 顯示當前版本
  about:memory - 顯示本機瀏覽器記憶體使用狀況
  about:plugins - 顯示已安裝外掛
  about:histograms - 顯示歷史記錄
  about:dns - 顯示DNS狀態
  about:cache - 顯示快取頁面
  about:gpu -是否有硬體加速
  about:flags -開啟一些外掛 //使用後彈出這麼些東西:“請小心,這些實驗可能有風險”,不知會不會搞亂俺的配置啊!
  chrome://extensions/ - 檢視已經安裝的擴充套件

三、 chrome實用引數 

  –user-data-dir=”[PATH]” 指定使用者資料夾User Data路徑,可以把書籤這樣的使用者資料儲存在系統分割槽以外的分割槽。
  –disk-cache-dir=”[PATH]“ 指定快取Cache路徑
  –disk-cache-size= 指定Cache大小,單位Byte
  –first run 重置到初始狀態,第一次執行
  –incognito 隱身模式啟動
  –disable-javascript 禁用Javascript
  –omnibox-popup-count=”num” 將位址列彈出的提示選單數量改為num個。我都改為15個了。
  –user-agent=”xxxxxxxx” 修改HTTP請求頭部的Agent字串,可以通過about:version頁面檢視修改效果
  –disable-plugins 禁止載入所有外掛,可以增加速度。可以通過about:plugins頁面檢視效果
  –disable-javascript 禁用JavaScript,如果覺得速度慢在加上這個
  –disable-java 禁用java
  –start-maximized 啟動就最大化
  –no-sandbox 取消沙盒模式
  –single-process 單程序執行
  –process-per-tab 每個標籤使用單獨程序
  –process-per-site 每個站點使用單獨程序
  –in-process-plugins 外掛不啟用單獨程序
  –disable-popup-blocking 禁用彈出攔截
  –disable-plugins 禁用外掛
  –disable-images 禁用影象
  –incognito 啟動進入隱身模式
  –enable-udd-profiles 啟用賬戶切換選單
  –proxy-pac-url 使用pac代理 [via 1/2]
  –lang=zh-CN 設定語言為簡體中文
  –disk-cache-dir 自定義快取目錄
  –disk-cache-size 自定義快取最大值(單位byte)
  –media-cache-size 自定義多媒體快取最大值(單位byte)
  –bookmark-menu 在工具 欄增加一個書籤按鈕
  –enable-sync 啟用書籤同步
  –single-process 單程序執行Google Chrome
  –start-maximized 啟動Google Chrome就最大化
  –disable-java 禁止Java
  –no-sandbox 非沙盒模式執行

  

selenium抓取chromedriver的network

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
d = DesiredCapabilities.CHROME
d['loggingPrefs'] = {'performance': 'ALL'}
driver = webdriver.Chrome( desired_capabilities=d)
driver.get("https://www.baidu.com")
register = driver.find_element_by_partial_link_text("登入")
register.click()
for entry in driver.get_log('performance'):
    print(entry)

參考:https://blog.csdn.net/Ambulong/article/details/52672384


參考博文:https://blog.csdn.net/zwq912318834/article/details/78933910
Selenium啟動Chrome時配置選項 https://blog.csdn.net/liaojianqiu0115/article/details/78353267
Chrome命令列設定 https://peter.sh/experiments/chromium-command-line-switches/
selenium操作chrome時的一些配置 https://blog.csdn.net/hellozhxy/article/details/80245296


selenium設定phantomjs請求頭

#-------------------------------------------------------------------------------------
#設定phantomjs請求頭和代理方法一:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# 設定代理
service_args = [
    '--proxy=%s' % ip_html,       # 代理 IP:prot(eg:192.168.0.28:808)
    '--proxy-type=http',          # 代理型別:http/https
    '--load-images=true',         # 關閉圖片載入(可選)在linux下有bug,這樣設定的話會導致記憶體不斷增加,最後掛掉
    '--disk-cache=true',          # 開啟快取(可選)
    '--ignore-ssl-errors=true'    # 忽略https錯誤(可選)
]

#設定請求頭
user_agent = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
    )
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = user_agent
driver = webdriver.PhantomJS(executable_path="phantomjs.exe",
                             desired_capabilities=dcap,
                             service_args=service_args)

driver.get(url='http://www.baidu.com')




#-------------------------------------------------------------------------------------
#設定phantomjs請求頭和代理方法二:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.proxy import ProxyType
desired_capabilities = DesiredCapabilities.PHANTOMJS.copy()
# 從USER_AGENTS列表中隨機選一個瀏覽器頭,偽裝瀏覽器
user_agent = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
    )
desired_capabilities["phantomjs.page.settings.userAgent"] = user_agent
# 不載入圖片,爬頁面速度會快很多
desired_capabilities["phantomjs.page.settings.loadImages"] = False

# 利用DesiredCapabilities(代理設定)引數值,重新開啟一個sessionId,
# 相當於瀏覽器清空快取後,加上代理重新訪問一次url
proxy = webdriver.Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy ='192.168.0.28:808'
# 將代理設定新增到webdriver.DesiredCapabilities.PHANTOMJS中
proxy.add_to_capabilities(desired_capabilities)
# 開啟帶配置資訊的phantomJS瀏覽器
driver = webdriver.PhantomJS(executable_path='phantomjs.exe',
                             desired_capabilities=desired_capabilities)
driver.start_session(desired_capabilities)

driver.get(url='http://www.baidu.com')

# ==========================或者==========================
from    selenium import  webdriver
proxy=webdriver.Proxy()
proxy.proxy_type=ProxyType.MANUAL
proxy.http_proxy='192.168.0.28:808'
# 將代理設定新增到webdriver.DesiredCapabilities.PHANTOMJS中
proxy.add_to_capabilities(webdriver.DesiredCapabilities.PHANTOMJS)
browser.start_session(webdriver.DesiredCapabilities.PHANTOMJS)
browser.get('http://www.baidu.com')

#-------------------------------------------------------------------------------------
# 還原為系統代理
proxy=webdriver.Proxy()
proxy.proxy_type=ProxyType.DIRECT
proxy.add_to_capabilities(webdriver.DesiredCapabilities.PHANTOMJS)
browser.start_session(webdriver.DesiredCapabilities.PHANTOMJS)
browser.get('http://1212.ip138.com/ic.asp')

火狐相關設定

# -*- coding: utf-8 -*-
from selenium import webdriver
options = webdriver.FirefoxOptions()
#火狐無頭模式
options.add_argument('--headless')
options.add_argument('--disable-gpu')
# options.add_argument('window-size=1200x600')

driver_path = webdriver.Firefox(executable_path='geckodriver.exe',
                                firefox_options=options)


常用的瀏覽器請求頭User-Agent

https://blog.csdn.net/mouday/article/details/80182397


博文參考:
https://blog.csdn.net/xc_zhou/article/details/80823855
https://www.zhihu.com/question/35547395
https://segmentfault.com/a/1190000013067705
https://www.cnblogs.com/lgh344902118/p/6339378.html