|
在我们进行数据采集的过程中,经常会遇到有些复杂网站,升级频繁破解不易,实在令人头大。在遇到这样的情况时我们可以应对的策略是,为了提高采集效率,在数据量采集量不太大的情况下,可以考虑使用无头浏览器+代理IP进行数据采集。头浏览器有很多,但目前有完善维护的其实不多,这里我们推荐大家selenium+chrome。 那么我使用无头浏览器时要怎么加上代理ip进行数据采集呢?这里给大家示例下如何在爬虫程序里面添加上代理ip,只针对于selenium+chrome,有其他语言需求的可以在这里了解下https://www.16yun.cn/。 简单示例如下: from selenium import webdriver import string import zipfile # 代理服务器(产品官网 www.16yun.cn) proxyHost = "t.16yun.cn" proxyPort = "3111" # 代理验证信息 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'/tmp/{}_{}@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", "<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: ["localhost"] } }; 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'] ); """ ).substitute( host=proxy_host, port=proxy_port, username=proxy_username, password=proxy_password, scheme=scheme, ) print(background_js) 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) # 关闭webdriver的一些标志 # option.add_experimental_option('excludeSwitches', ['enable-automation']) driver = webdriver.Chrome( chrome_options=option, executable_path="./chromdriver" ) # 修改webdriver get属性 # script = ''' # Object.defineProperty(navigator, 'webdriver', { # get: () => undefined # }) # ''' # driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script}) driver.get("https://httpbin.org/ip")关于无头浏览器的使用还有很多的注意事项,具体的需要在实践中去学习和解决才能掌握。
若有收获,就点个赞吧
|
|