selenium+PhantomJs爬虫

需求:urlopen得到的数据不正确,发现是因为界面经过js渲染,故使用selenium尝试一下。

1. 安装

brew install selenium
brew install phantoms

配合Chrome使用需要安装chromedriver:

  1. 下载地址 注意驱动版本与浏览器版本要对应
  2. 将下载的可执行文件(chromedriver) 移动到/usr/bin下

最后,把 phantoms 路径添加到 bash 中,source一下生效。

export PHANTOMJS_HOME=/usr/local/Cellar/phantomjs/phantomjs-2.1.1-macosx
export PATH=$PATH:$PHANTOMJS_HOME/bin	

2. 使用selenium

简单测试一下:

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")     

获取网页内容: driver.page_source

3. selenium+PhantomJs

	browser = webdriver.PhantomJS(executable_path="/usr/local/Cellar/phantomjs/phantomjs-2.1.1-macosx/bin/phantomjs")
        browser.start_session(webdriver.DesiredCapabilities.PHANTOMJS)
        # 设置超时时间
        browser.set_page_load_timeout(50)
        browser.set_script_timeout(50)

        browser.get("http://www.baidu.com")            

可以通过 browser.find_element_by_class_name 等接口拿到想要的数据。

保存截图

	browser.save_screenshot("baidu.png")

4. 设置代理

       # 利用DesiredCapabilities(代理设置)参数值
        proxy = webdriver.Proxy()
        proxy.proxy_type = ProxyType.MANUAL
        proxy.http_proxy = ip //ip地址
        # 将代理设置添加到 webdriver.DesiredCapabilities.PHANTOMJS 中		proxy.add_to_capabilities(webdriver.DesiredCapabilities.PHANTOMJS) 

5. 设置header

       desired_capabilities = webdriver.DesiredCapabilities.PHANTOMJS.copy()
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'User-Agent': ' ' 
        }
        for key, value in headers.items():
            desired_capabilities['phantomjs.page.customHeaders.{}'.format(key)] = value
        
        browser = webdriver.PhantomJS(desired_capabilities=desired_capabilities,executable_path="/usr/local/Cellar/phantomjs/phantomjs-2.1.1-macosx/bin/phantomjs")   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值