• 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和代理的方法。

  • 相关阅读:
    TDengine 基本操作
    Spark 提交运行 保存结果 流程控制
    Redis 分布式锁
    Linux 基础命令
    HIVE 分桶模式
    EX: 这里是收集的面试题
    使用python批量创建 mysql 表
    Navicat写MySQL触发器,用来同步表
    NXOpen 创建体获取所有边、边端点信息,过虑竖边倒圆水平边倒角
    NXOpen遍历实体移除参数和改色
  • 原文地址:https://www.cnblogs.com/it-tsz/p/10591673.html
Copyright © 2020-2023  润新知