码迷,mamicode.com
首页 > Web开发 > 详细

Selenium中通过修改User-Agent标识将PhantomJS伪装成Chrome浏览器

时间:2017-11-21 10:45:59      阅读:1821      评论:0      收藏:0      [点我收藏+]

标签: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浏览器

标签:python爬虫

原文地址:http://6230973.blog.51cto.com/6220973/1983669

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!