python + seleinum +phantomjs 設置headers和proxy代理
最近因為工作需要使用selenium+phantomjs無頭瀏覽器,其中遇到了一些坑,記錄一下,尤其是關於phantomjs設置代理的問題。
基本使用
首先在python中導入使用的包,其中webdriver是要創建無頭瀏覽器對象的模塊,DesiredCapabilites這個類是瀏覽器對象的一些選項設置。
-
from selenium import webdriver
-
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
-
-
# 初始化瀏覽器對象
-
desired_cap = DesiredCapabilities.PHANTOMJS.copy()
-
driver = webdriver.PhantomJS(desired_capabilities=desired_cap)
修改請求頭
在使用爬蟲的過程中我們需要修改請求投中的user-agent防止被反爬,修改過程如下
-
desired_cap = DesiredCapabilities.PHANTOMJS.copy()
-
# 修改請求頭中的UA
-
desired_cap[ 'phantomjs.page.settings.userAgent'] = 'xxxxxx'
-
# 設置其他請求投信息,其中key為要修改的請求投鍵名
-
desired_cap[ 'phantomjs.page.customHeaders.{}'.format(key)] = 'xxxx'
-
driver = webdriver.PhantomJS(desired_capabilities=desired_cap)
設置代理
在使用爬蟲過程中,經常需要使用代理ip,網上關於這方面資料較少,我也是搜集了好久,記錄一下
ip代理有靜態ip代理和動態ip代理,先說靜態ip,靜態ip就是134.119.184.92:1080這樣的代理,不需要使用驗證信息,使用方法如下:
-
-
proxy = [
-
'--proxy=%s' % "218.60.8.83:3129",
-
'--proxy-type=http',
-
'--ignore-ssl-errors=true',
-
]
-
-
-
drive = webdriver.PhantomJS(service_args=proxy)
-
-
-
drive.set_page_load_timeout( 10)
-
drive.set_script_timeout( 10)
-
-
-
drive. get('http://www.baidu.com')
以上是靜態代理設置方法,但是我們時候使用的是動態代理,設置方法有所變化,需要在參數里加上驗證使用的用戶名和密碼,代碼如下:
-
-
proxy = [
-
'--proxy=%s:%s' % (proxyHost, proxyPort),
-
'--proxy-type=http',
-
'--proxy-auth=%s:%s' % (proxyUser, proxyPass),
-
'--ignore-ssl-errors=true',
-
]
-
-
-
drive = webdriver.PhantomJS(service_args=proxy)
-
-
-
drive.set_page_load_timeout( 10)
-
drive.set_script_timeout( 10)
-
-
-
drive. get('http://www.baidu.com')
以上就是使用selenium + phantomjs無頭瀏覽器設置headers和代理的方法。