一尘不染

Python中的Selenium PhantomJS自定义标头

selenium

我想将“自定义标头”添加到python中的Selenium PhantomJS中。这些是我要添加的标题。

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'
          }

这是我正在使用的代码:

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()

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

请帮忙。


阅读 380

收藏
2020-06-26

共1个答案

一尘不染

以以下方式设置标题:

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

然后开始使用驱动程序:

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