selenium/webdriver/common/proxy.py
selenium webdriver
测试或进行爬虫时,如果未在目标服务的白名单内,随着爬取的频率增多会被禁止访问目标服务;综上,所以Proxy类提供了一些反爬虫策略,
class ProxyType:
"""
Set of possible types of proxy.
Each proxy type has 2 properties:
'ff_value' is value of Firefox profile preference,
'string' is id of proxy type.
"""
DIRECT = ProxyTypeFactory.make(0, 'DIRECT') # Direct connection, no proxy (default on Windows).
MANUAL = ProxyTypeFactory.make(1, 'MANUAL') # Manual proxy settings (e.g., for httpProxy).
PAC = ProxyTypeFactory.make(2, 'PAC') # Proxy autoconfiguration from URL.
RESERVED_1 = ProxyTypeFactory.make(3, 'RESERVED1') # Never used.
AUTODETECT = ProxyTypeFactory.make(4, 'AUTODETECT') # Proxy autodetection (presumably with WPAD).
SYSTEM = ProxyTypeFactory.make(5, 'SYSTEM') # Use system settings (default on Linux).
UNSPECIFIED = ProxyTypeFactory.make(6, 'UNSPECIFIED') # Not initialized (for internal use).
代理类型 | 说明 |
---|---|
| 直接连接,无代理(Windows上的默认设置 |
| 手动代理设置(例如,对于 |
| 来自URL的代理自动配置 |
| 从未使用过 |
| 代理自动检测(可能是WPAD) |
| 使用系统设置(Linux上的默认设置) |
| 未初始化(供内部使用) |
class ProxyTypeFactory:
"""
Factory for proxy types.
"""
@staticmethod
def make(ff_value, string):
return {'ff_value': ff_value, 'string': string}
参数 | 说明 |
---|---|
| Firefox配置文件首选项的值 |
| 代理类型的ID |
class Proxy(object):
"""
Proxy contains information about proxy type and necessary proxy settings.
"""
proxyType = ProxyType.UNSPECIFIED
autodetect = False
ftpProxy = ''
httpProxy = ''
noProxy = ''
proxyAutoconfigUrl = ''
sslProxy = ''
socksProxy = ''
socksUsername = ''
socksPassword = ''
@property
def http_proxy(self):
"""
Returns http proxy setting.
"""
return self.httpProxy
@http_proxy.setter
def http_proxy(self, value):
"""
Sets http proxy setting.
:Args:
- value: The http proxy value.
"""
self._verify_proxy_type_compatibility(ProxyType.MANUAL)
self.proxyType = ProxyType.MANUAL
self.httpProxy = value
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
profile = FirefoxProfile()
# 设置成手动代理
profile.set_preference("network.proxy.type", 1)
# 设置代理ip
profile.set_preference("network.proxy.http", "ip")
# 设置代理端口
profile.set_preference("network.proxy.http_port", port)
# 协议默认共用此ip、端口
profile.set_preference("network.proxy.share_proxy_settings", True)
# 启动配置
driver= webdriver.Firefox(profile)
# 打开浏览器
driver.get('xxxxx')
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。