1. 程式人生 > >Selenium中通過修改User-Agent標識將PhantomJS偽裝成Chrome瀏覽器

Selenium中通過修改User-Agent標識將PhantomJS偽裝成Chrome瀏覽器

python爬蟲

文章首發個人博客:http://zmister.com/archives/179.html


Python爬蟲、GUI開發、滲透測試、機器學習,盡在http://zmister.com/


在寫爬蟲的過程中,出於系統環境或是效率的問題,我們經常使用PhantomJS作為Selenium操縱的瀏覽器webdriver,而不是直接使用Chrome或FireFox的webdriver,盡管後者更加直觀。

PhantomJS的優點雖然很多,但是缺點卻也不少,有一個不能稱之為缺點的缺點就是,PhantomJS的瀏覽器標識是“PhantomJS”(勇敢的做自己竟然有錯……:))

PhantomJS的標識本沒有什麽問題,但是在現在越來越多的網站不斷升級自己的反爬蟲技術的情況下,PhantomJS顯然成為了一個和“requests”一樣的靶子。

只要服務器後臺識別到訪問者的User-Agent為PhantomJS,就有可能被服務器判定為爬蟲行為,而導致爬蟲失效。

如同在requests中修改header頭域以偽裝成瀏覽器一樣,我們可以在Selenium中將PhantomJS的瀏覽器標識修改為任意瀏覽器的標識。下面介紹一下:

PhantomJS的瀏覽器標識

首先來看看PhantomJS的瀏覽器標識是怎樣的。

http://service.spiritsoft.cn/ua.html是一個獲取瀏覽器標識User-Agent的網站,訪問它就會顯示當前使用的瀏覽器的標識:

技術分享圖片

我們使用Selunium操縱PhantomJS訪問http://service.spiritsoft.cn/ua.html,看看返回的結果:

# coding:utf-8

from selenium import webdriver
from bs4 import BeautifulSoup

def defaultPhantomJS():
    driver = webdriver.PhantomJS(executable_path=r"D:\phantomjs.exe")
    driver.get(‘http://service.spiritsoft.cn/ua.html‘)
    source = driver.page_source
    soup = BeautifulSoup(source,‘lxml‘)
    user_agent = soup.find_all(‘td‘,attrs={‘style‘:‘height:40px;text-align:center;font-size:16px;font-weight:bolder;color:red;‘})
    for u in user_agent:
        print(u.get_text().replace(‘\n‘,‘‘).replace(‘ ‘,‘‘))
    driver.close()

技術分享圖片

很明顯的有PhantomJS的痕跡。

接下來,我們對PhantomJS的瀏覽器標識進行修改。

偽裝成Chrome

引入一個關鍵的模塊——DesiredCapabilities:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

這個模塊是幹什麽用的呢?我們看看源碼的解釋:

class DesiredCapabilities(object):
    """
    Set of default supported desired capabilities.

    Use this as a starting point for creating a desired capabilities object for
    requesting remote webdrivers for connecting to selenium server or selenium grid.

描述了一系列封裝的瀏覽器屬性的鍵值對,大致就是用來設置webdriverde的屬性。我們使用它來設置PhantomJS的User-Agent。

首先將DesiredCapabilities轉換為一個字典,方便添加鍵值對

dcap = dict(DesiredCapabilities.PHANTOMJS)

然後添加一個瀏覽器標識的鍵值對:

dcap[‘phantomjs.page.settings.userAgent‘] = (‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36‘)

最後,在實例化PhantomJS中設為參數:

driver = webdriver.PhantomJS(executable_path=r"D:\phantomjs.exe",desired_capabilities=dcap,service_args=[‘--ignore-ssl-errors=true‘])

完整的代碼如下:

# coding:utf-8

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

def editUserAgent():
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap[‘phantomjs.page.settings.userAgent‘] = (‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36‘)
    driver = webdriver.PhantomJS(executable_path=r"D:\phantomjs.exe",desired_capabilities=dcap,service_args=[‘--ignore-ssl-errors=true‘])
    driver.get(‘http://service.spiritsoft.cn/ua.html‘)
    source = driver.page_source
    soup = BeautifulSoup(source, ‘lxml‘)
    user_agent = soup.find_all(‘td‘, attrs={
        ‘style‘: ‘height:40px;text-align:center;font-size:16px;font-weight:bolder;color:red;‘})
    for u in user_agent:
        print(u.get_text().replace(‘\n‘, ‘‘).replace(‘ ‘, ‘‘))
    driver.close()

if __name__ == ‘__main__‘:
    editUserAgent()

我們運行一下代碼:

技術分享圖片

成功地將PhantomJS標識為了Chrome瀏覽器。

是不是很簡單?


本文出自 “州的先生” 博客,轉載請與作者聯系!

Selenium中通過修改User-Agent標識將PhantomJS偽裝成Chrome瀏覽器