Selenium之PhantomJS相关设置
设置PhantomJS请求头
默认情况下:
from selenium import webdriver
import time
driver = webdriver.PhantomJS()
driver.get('http://httpbin.org/user-agent')
print(driver.page_source)
driver.close()
设置User-Agent
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
user_agent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.3 Safari/537.36"
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = user_agent
dcap["phantomjs.page.customHeaders.User-Agent"] = user_agent
driver = webdriver.PhantomJS(desired_capabilities=dcap)
driver.get('http://httpbin.org/user-agent')
print(driver.page_source)
driver.close()
User-Agent已经变成指定的内容
设置PhantomJS不加载图片
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
SERVICE_ARGS = ['--load-images=false', '--disk-cache=true','--ignore-ssl-errors=true']
driver = webdriver.PhantomJS(service_args=SERVICE_ARGS)
driver.get('https://www.baidu.com')
driver.save_screenshot('baidu.png')
driver.close()
SERVICE_ARGS 常用的参数
--cookies-file=/path/to/cookies.txt # 指定cookies文件
--disk-cache=[true|false] # 是否应用磁盘缓存
--ignore-ssl-errors=[true|false] # 是否忽略ssl证书错误
--load-images=[true|false] # 是否加载图片
--output-encoding=encoding # 指定输出编码 默认是utf8
--proxy=address:port # 指定代理服务器,格式是--proxy=192.168.1.42:8080
--proxy-type=[http|socks5|none] # 指定代理服务器协议类型
--proxy-auth # 代理服务器认证,格式是--proxy-auth=username:password
更多设置可以参考官网
参数设置