1. 程式人生 > 其它 >selenium設定Chrome代理、UA和Cookie

selenium設定Chrome代理、UA和Cookie

一、selenium設定Chrome User-Agent+代理
先上程式碼
這裡我直接用的UA輪子,隨機取出一個來設定
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
headers = {'User-Agent': UserAgent().random} #從UA輪子裡隨機抽選一個用作配置,也可以自己手動設定
print(headers) #自己手動設定,格式像這樣(看輸出)
proxy = "127.0.0.1:8080
" #這裡是我自己本地開的一個代理服務用作測試 ops = Options() ops.add_argument('User-Agent={}'.format(headers['User-Agent'])) #配置為自己設定的UA ops.add_argument('--proxy-server=http://%s' % proxy) #新增代理 格式為ip:port browser = webdriver.Chrome(options=ops) browser.get('http://192.168.31.130/dvwa/index.php')
輸出:
{'User-Agent': 'Mozilla/5.0 (X11; NetBSD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'}
可在burpsuit上看到代理的流量說明代理成功,並且UA也已設定為自己配置的UA
二、selenium設定Chrome Cookie
登入後可看到Cookie長這樣
錯誤示例
這估計很多人都踩了這個坑
browser.delete_all_cookies()  # 刪除原來的cookie
browser.add_cookie({'think_lang': 'zh-cn', 'PHPSESSID': '6be4ba542aeecd9bef7967269add2835'})
browser.get('http://192.168.31.130/dvwa/index.php')

然後就會報這個錯

InvalidArgumentException

: Message: invalid argument: missing 'name'

正確示例

我這樣寫是為了方便大家更清楚當Cookie有多個 name 和 value 時該如何設定

cookie1 = {'name': 'security', 'value': 'impossible'}
cookie2 = {'name': 'PHPSESSID', 'value': 'n5u6pc2lul897cdca7pek6s713'}
browser.delete_all_cookies()  # 刪除原來的cookie
browser.add_cookie(cookie1)
browser.add_cookie(cookie2)
browser.get('http://192.168.31.130/dvwa/index.php')

當然你也可以用一個for迴圈顯得更專業(doge)

cookie = {
    'security': 'impossible',
    'PHPSESSID': 'n5u6pc2lul897cdca7pek6s713'
}
browser.delete_all_cookies()  # 刪除原來的cookie
for name, value in cookie.items():
    browser.add_cookie({'name':name,'value':value})
browser.get('http://192.168.31.130/dvwa/index.php')

完整程式碼

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
headers = {'User-Agent': UserAgent().random} #從UA輪子裡隨機抽選一個用作配置,也可以自己手動設定
print(headers) #自己手動設定,格式像這樣(看輸出)
proxy = "127.0.0.1:8080" #這裡是我自己本地開的一個代理服務用作測試
ops = Options()
ops.add_argument('User-Agent={}'.format(headers['User-Agent'])) #配置為自己設定的UA
ops.add_argument('--proxy-server=http://%s' % proxy) #新增代理 格式為ip:port
browser = webdriver.Chrome(options=ops)
browser.get('http://192.168.31.130/dvwa/index.php')
cookie = {
    'security': 'impossible',
    'PHPSESSID': 'n5u6pc2lul897cdca7pek6s713'
}
browser.delete_all_cookies()  # 刪除原來的cookie
for name, value in cookie.items():
    browser.add_cookie({'name':name,'value':value})
browser.get('http://192.168.31.130/dvwa/index.php')

這裡執行完如果想退出selenium驅動的瀏覽器記得用browser.quit(),手動叉掉的話程序可能沒關掉

browser.quit()

程式碼功能:代理並設定自定義UA然後用Cookie自動登入成功