1、设置代理服务器
通过ProxyHandler在request中设置使用代理服务器,代理的使用非常简单,可以在专业网站上购买稳定的ip地址,也可以在网上寻找免费的ip代理。
免费开放代理基本没有成本。我们可以在一些代理网站上收集这些免费代理。如果测试后可以使用,我们可以在爬虫上收集它们。
2、selenium使用代理ip
selenium在使用带有用户名和密码的代理ip时,不能使用无头模式。
def create_proxy_auth_extension(proxy_host, proxy_port,
proxy_username, proxy_password,
scheme='http', plugin_path=None):
if plugin_path is None:
plugin_path = r'./proxy_auth_plugin.zip'
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = string.Template(
"""
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "${scheme}",
host: "${host}",
port: parseInt(${port})
},
bypassList: ["foobar测试数据"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "${username}",
password: "${password}"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
chrome.webRequest.onBeforeSendHeaders.addListener(function (details) {
details.requestHeaders.push({name:"connection",value:"close"});
return {
requestHeaders: details.requestHeaders
};
},
{urls: ["<all_urls>"]},
['blocking']
);
"""
).substitute(
host=proxy_host,
port=proxy_port,
username=proxy_username,
password=proxy_password,
scheme=scheme,
)
with zipfile.ZipFile(plugin_path, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
return plugin_path
chrome_options = webdriver.ChromeOptions()
proxy_auth_plugin_path = create_proxy_auth_extension(
proxy_host=proxyHost,
proxy_port=proxyPort,
proxy_username=proxyUser,
proxy_password=proxyPass)
chrome_options.add_extension(proxy_auth_plugin_path)
driver = webdriver.Chrome(chrome_options=chrome_options)许多网站会在一定时间内检测到某个IP的访问次数(通过流量统计、系统日志等),如果访问次数多得不像正常人,就会禁止该IP的访问。因此,我们可以设置一些代理服务器,每隔一段时间更换一个代理,即使IP被禁止,仍然可以更换IP继续爬行。
以上就是代理IP在爬虫中使用,在掌握了基本的爬虫知识后,我们可以结合代理ip,加快获取数据的速度。如果大家想测试使用下,可以尝试 品易云http代理ip ,免费测试包含各种类ip资源,调用IP量! 更多常见问题解决: ip
推荐操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did248887