当前位置: 首页 > 后端技术 > Python

Selenium爬虫注意事项

时间:2023-03-26 00:01:31 Python

有些网站有严格的反爬策略,一般的爬虫无法及时采集数据。分析网站反爬虫策略需要花费大量的时间和精力进行研发。因此,使用Selenium模拟用户浏览器进行数据访问,快速实现数据采集是一个较好的解决方案。但是在Selenium爬虫的实际部署中,为了实现稳定持续的数据采集,需要避免一些常见的问题,包括:1、开发模式设置为开发者模式,防止被各大网站识别。Seleniumfromselenium.webdriverimport使用ChromeOptionsoption=ChromeOptions()option.add_experimental_option('excludeSwitches',['enable-automation'])#开启实验功能browser=webdriver.Chrome(options=option)#修改get方法script='''Object.defineProperty(navigator,'webdriver',{get:()=>undefined})'''browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",{"source":script})2.如果版本登录生成的cookie不匹配,会操作失败,所以建议安装chrome和对应的驱动:下载对应版本的chrome驱动下载chromehttps://www.google.com/chrome/下载对应版本驱动程序https://chromedriver.chromium.org/downloads3.选择爬虫代理为了避免频繁访问目标网站,必须配置爬虫代理。由于Selenium调用浏览器,需要稳定的网络连接、低延迟、高并发,所以推荐使用隧道转发代理IP。目前市面上的隧道转发代理产品大多需要代码写入用户名和密码。认证方式,代码参考如下fromseleniumimportwebdriveimportstringimportzipfile#代理服务器(产品官网www.16yun.cn)proxyHost="t.16yun.cn"proxyPort="31111"#代理认证信息proxyUser="用户名"proxyPass="password"defcreate_proxy_auth_extension(proxy_host,proxy_port,proxy_username,proxy_password,scheme='http',plugin_path=None):如果plugin_path为None:plugin_path=r'D:/{}_{}@t.16yun。zip'.format(proxy_username,proxy_password)manifest_json="""{"version":"1.0.0","manifest_version":2,"name":"16YUNProxy","permissions":["proxy","tabs","unlimitedStorage","storage","","webRequest","webRequestBlocking"],"background":{"scripts":["background.js"]},"minimum_chrome_version":"22.0.0"}"""background_js=string.Template("""varconfig={mode:"fixed_servers",rules:{singleProxy:{scheme:"${scheme}",host:"${host}",port:parseInt(${port})},bypassList:["foobar.com"]}};chrome.proxy.settings.set({value:config,scope:"regular"},函数(){});functioncallbackFn(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,)withzipfile.ZipFile(plugin_path,'w')aszp:zp.writestr("manifest.json",manifest_json)zp.writestr("background.js",background_js)returnplugin_pathproxy_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)#修改webdriverget属性#script='''#Object.defineProperty(navigator,'webdriver',{#get:()=>undefined#})#'''#driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",{"source":脚本})driver.get("http://httpbin.org/ip")请注意plugin_path中的r'D:/{}_{}@t.16yun.zip'是存放代理认证信息的临时目录和文件,可根据本地文件目录权限动态配置,否则读取失败导致程序在第一次运行时,提示手动输入用户名和密码认证信息