在代理服务器后面运行selenium

Ary*_*att 13 python proxy selenium web-scraping selenium-webdriver

我一直在使用selenium进行自动浏览器模拟和python中的web抓取,它对我来说效果很好.但现在,我必须在代理服务器后面运行它.因此,现在selenium打开窗口但由于未在打开的浏览器上设置代理设置而无法打开请求的页面.目前的代码如下(样本):

from selenium import webdriver

sel = webdriver.Firefox()
sel.get('http://www.google.com')
sel.title
sel.quit()
Run Code Online (Sandbox Code Playgroud)

如何更改上面的代码现在也可以使用代理服务器?

ale*_*cxe 23

您需要设置所需的功能或浏览器配置文件,如下所示:

profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", "proxy.server.address")
profile.set_preference("network.proxy.http_port", "port_number")
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)
Run Code Online (Sandbox Code Playgroud)

另见相关主题:


小智 8

官方的Selenium文档(http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#using-a-proxy)提供了有关使用代理的明确且有用的指南.对于Firefox(您的示例代码中的首选浏览器),您应该执行以下操作:

from selenium import webdriver
from selenium.webdriver.common.proxy import *

myProxy = "host:8080"

proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy': '' # set this value as desired
    })

driver = webdriver.Firefox(proxy=proxy)
Run Code Online (Sandbox Code Playgroud)