PhantomJS自定义标头

PhantomJS自定义标头

本文介绍了Python中的Selenium PhantomJS自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中将自定义标头"添加到Selenium PhantomJS中.这些是我要添加的标题.

I want to add "custom headers" to Selenium PhantomJS in python.These are the headers I wanna add.

headers = { 'Accept':'*/*',
            'Accept-Encoding':'gzip, deflate, sdch',
            'Accept-Language':'en-US,en;q=0.8',
            'Cache-Control':'max-age=0',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
          }

这是我正在使用的代码:

This is the code I am working with:

from selenium import webdriver

service_args = [
    '--proxy=127.0.0.1:9999',
    '--proxy-type=socks5',
    ]
driver = webdriver.PhantomJS(service_args=service_args)


driver.set_window_size(1120, 550)
driver.get("https://duckduckgo.com/")
driver.find_element_by_id('search_form_input_homepage').send_keys("realpython")
driver.find_element_by_id("search_button_homepage").click()
print driver.current_url
driver.quit()

如何修改包含这些自定义标头的代码?

How do I modify the code incorporating those custom headers ?

请帮助.

推荐答案

以以下方式设置标头:

from selenium import webdriver


headers = { 'Accept':'*/*',
    'Accept-Encoding':'gzip, deflate, sdch',
    'Accept-Language':'en-US,en;q=0.8',
    'Cache-Control':'max-age=0',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
}

for key, value in enumerate(headers):
    capability_key = 'phantomjs.page.customHeaders.{}'.format(key)
    webdriver.DesiredCapabilities.PHANTOMJS[capability_key] = value

然后开始使用驱动程序:

Then start work with your driver:

service_args = [
    '--proxy=127.0.0.1:9999',
    '--proxy-type=socks5',
]
driver = webdriver.PhantomJS(service_args=service_args)
# ...............

这篇关于Python中的Selenium PhantomJS自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 05:53