今天給你們分享的是如何在爬取數據的時候防止 IP被封,今天給你們分享兩種方法,但願你們能夠認真學習,不再用擔憂被封IP啦。python
第一種:web
下降訪問速度,咱們可使用 time模塊中的sleep,使程序每運行一次後就睡眠1s,這樣的話就能夠大大的減小ip被封的概率chrome
第二種:json
爲了提升效率,咱們可使用代理 ip來解決,ip是億牛雲的動態轉發代理,如下是代理配置過程的示例服務器
from selenium import webdriver學習
import stringui
import zipfilechrome-extension
# 代理服務器url
proxyHost = "t.16yun.cn"spa
proxyPort = "31111"
# 代理隧道驗證信息
proxyUser = "username"
proxyPass = "password"
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 'C:/{}_{}@t.16yun.zip' .format(proxy_username, proxy_password)
manifest_json = """ { "version": "1.0.0", "manifest_version": 2, "name": "16YUN Proxy", "permissions": [ "proxy", "tabs", "unlimitedStorage", "storage", "", "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.com"] } };
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) { return { authCredentials: { username: "${username}", password: "${password}" } }; }
chrome.webRequest.onAuthRequired.addListener( callbackFn, {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
proxy_auth_plugin_path = create_proxy_auth_extension(
proxy_host=proxyHost,
proxy_port=proxyPort,
proxy_username=proxyUser,
proxy_password=proxyPass)
option = webdriver.ChromeOptions()
option.add_argument( "--start-maximized" )
# 如報錯 chrome-extensions
# option.add_argument("--disable-extensions")
option.add_extension(proxy_auth_plugin_path)
driver = webdriver.Chrome(chrome_options=option)
driver.get( "http://httpbin.org/ip" )
好 了,今天關於python學習的分享就到這裏,上邊的那段代碼能夠直接使用,可是裏邊的代理應該已通過期,你們在使用的時候可能須要聯繫代理商開通服務,最後呢但願你們可以收藏起來,要記得作筆記哦。好記性不如爛筆頭。