python + seleinum +phantomjs 設置headers和proxy代理


python + seleinum +phantomjs 設置headers和proxy代理

最近因為工作需要使用selenium+phantomjs無頭瀏覽器,其中遇到了一些坑,記錄一下,尤其是關於phantomjs設置代理的問題。

基本使用

首先在python中導入使用的包,其中webdriver是要創建無頭瀏覽器對象的模塊,DesiredCapabilites這個類是瀏覽器對象的一些選項設置。

  1.  
    from selenium import webdriver
  2.  
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  3.  
     
  4.  
    # 初始化瀏覽器對象
  5.  
    desired_cap = DesiredCapabilities.PHANTOMJS.copy()
  6.  
    driver = webdriver.PhantomJS(desired_capabilities=desired_cap)

修改請求頭

在使用爬蟲的過程中我們需要修改請求投中的user-agent防止被反爬,修改過程如下

  1.  
    desired_cap = DesiredCapabilities.PHANTOMJS.copy()
  2.  
    # 修改請求頭中的UA
  3.  
    desired_cap[ 'phantomjs.page.settings.userAgent'] = 'xxxxxx'
  4.  
    # 設置其他請求投信息,其中key為要修改的請求投鍵名
  5.  
    desired_cap[ 'phantomjs.page.customHeaders.{}'.format(key)] = 'xxxx'
  6.  
    driver = webdriver.PhantomJS(desired_capabilities=desired_cap)

設置代理

在使用爬蟲過程中,經常需要使用代理ip,網上關於這方面資料較少,我也是搜集了好久,記錄一下

ip代理有靜態ip代理和動態ip代理,先說靜態ip,靜態ip就是134.119.184.92:1080這樣的代理,不需要使用驗證信息,使用方法如下:

  1.  
    # 配置代理信息
  2.  
    proxy = [
  3.  
    '--proxy=%s' % "218.60.8.83:3129", # 設置的代理ip
  4.  
    '--proxy-type=http', # 代理類型
  5.  
    '--ignore-ssl-errors=true', # 忽略https錯誤
  6.  
    ]
  7.  
     
  8.  
    # 在初始化瀏覽器對象的時候可以接收一個service_args的參數,使用這個參數設置代理
  9.  
    drive = webdriver.PhantomJS(service_args=proxy)
  10.  
     
  11.  
    # 設置頁面加載和js加載超時時間,超時立即報錯,如下設置超時時間為10秒
  12.  
    drive.set_page_load_timeout( 10)
  13.  
    drive.set_script_timeout( 10)
  14.  
     
  15.  
    # 這樣代理就設置成功了,可以向百度發送請求驗證ip是否可用
  16.  
    drive. get('http://www.baidu.com')

 以上是靜態代理設置方法,但是我們時候使用的是動態代理,設置方法有所變化,需要在參數里加上驗證使用的用戶名和密碼,代碼如下:

  1.  
    # 代理設置如下:
  2.  
    proxy = [
  3.  
    '--proxy=%s:%s' % (proxyHost, proxyPort), # 代理服務器的域名
  4.  
    '--proxy-type=http', # 代理類型
  5.  
    '--proxy-auth=%s:%s' % (proxyUser, proxyPass), # 代理驗證所需的用戶名和密碼
  6.  
    '--ignore-ssl-errors=true', # 忽略https錯誤
  7.  
    ]
  8.  
     
  9.  
    # 在初始化瀏覽器對象的時候可以接收一個service_args的參數,使用這個參數設置代理
  10.  
    drive = webdriver.PhantomJS(service_args=proxy)
  11.  
     
  12.  
    # 設置頁面加載和js加載超時時間,超時立即報錯,如下設置超時時間為10秒
  13.  
    drive.set_page_load_timeout( 10)
  14.  
    drive.set_script_timeout( 10)
  15.  
     
  16.  
    # 這樣代理就設置成功了,可以向百度發送請求驗證ip是否可用
  17.  
    drive. get('http://www.baidu.com')

 以上就是使用selenium + phantomjs無頭瀏覽器設置headers和代理的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM