undetected-chromedriver

undetected-chromedriver

优化Selenium Chromedriver以绕过反爬虫检测

undetected-chromedriver是一个优化的Selenium Chromedriver补丁,可绕过多种反爬虫服务的检测。它自动下载并修补驱动程序,支持最新Chrome版本,适用于Python 3.6+。该项目可用于多种基于Chromium的浏览器,提供简单API,有效避免被识别为自动化工具。对Web自动化和爬虫项目具有重要价值。

undetected-chromedriverSelenium自动化反爬虫Chrome浏览器Github开源项目

undetected_chromedriver

https://github.com/ultrafunkamsterdam/undetected-chromedriver

Optimized Selenium Chromedriver patch which does not trigger anti-bot services like Distill Network / Imperva / DataDome / Botprotect.io Automatically downloads the driver binary and patches it.

  • Tested until current chrome beta versions
  • Works also on Brave Browser and many other Chromium based browsers, but you need to know what you're doing and needs some tweaking.
  • Python 3.6++**

Installation

pip install undetected-chromedriver

or , if you're feeling adventurous, install directly via github

pip install git+https://www.github.com/ultrafunkamsterdam/undetected-chromedriver@master     # replace @master with @branchname for other branches

Message for all

I will be putting limits on the issue tracker. It has beeen abused too long.
any good news?
Yes, i've opened Undetected-Discussions which i think will help us better in the long run.


What this is not

THIS PACKAGE DOES NOT, and i repeat DOES NOT hide your IP address, so when running from a datacenter (even smaller ones), chances are large you will not pass! Also, if your ip reputation at home is low, you won't pass!

Running following code from home , and from a datacenter.

import undetected_chromedriver as uc driver = uc.Chrome(headless=True,use_subprocess=False) driver.get('https://nowsecure.nl') driver.save_screenshot('nowsecure.png')
<div style="display:flex;flex-direction:row"> <img src="https://github.com/ultrafunkamsterdam/undetected-chromedriver/assets/21027969/262dad3e-33e9-4d67-b061-b30bc74ac9bc" width="720"/> <img src="https://github.com/ultrafunkamsterdam/undetected-chromedriver/assets/21027969/5e1d463b-3f88-496a-9a43-a39830f909da" width="720"/> </div> <!-- ![nowscure_local](https://github.com/ultrafunkamsterdam/undetected-chromedriver/assets/21027969/262dad3e-33e9-4d67-b061-b30bc74ac9bc) --> <!-- ![nowsecure_dc](https://github.com/ultrafunkamsterdam/undetected-chromedriver/assets/21027969/5e1d463b-3f88-496a-9a43-a39830f909da) -->

3.5.0

  • selenium 4.10 caused some issues. 3.5.0 is compatible and has selenium 4.9 or above pinned. I can't support <4.9 any longer.
  • Removed some kwargs from constructor: service_args, service_creationflags, service_log_path.
  • added find_elements_recursive generator function. which is more of a convenience funtion as lots of websites seem to serve different content from different frames, making it hard to use find_elements

3.4.5

  • What a week. Had the recent advancedments in Automation-Detection algorithms pwned (so i thought) with 3.4.0, but apparently, for some OS-es this caused an error when interacting with elements. Had to revert back using a different method, fix bugs, and now eventually was still able to stick to the initial idea (+ fixing bugs)
  • Update to chrome 110 caused another surprise, this time for HEADLESS users.
  • although headless is unsupported officially, i did patch it!
  • happy to announce IT IS NOW UNDETECTED AS WELL (but still unsupported ;))
  • special thanks here to @mdmintz and @abdulzain6
  • also special thanks to @sebdelsol for his help troughout the issues section completely voluntarily, you must be crazy :)

3.4.0

Big update! be careful as it -potentially- could break your code.

  • rewritten the anti-detection mechanism instead of removing and renaming variables, we just keep them, but prevent them from being injected in the first place. This will keep us safe from detection at least for the near future.

  • rewritten the file naming, to prevent ending up with 1000 of {randomstring}_chromedriver.exe 's instead it is just called undetected_chromedriver.exe

  • cleanup removed compat,v2 files and tests folder

3.2.0

  • added an example containing some typical webdriver code, answers to commonly asked questions, pitfalls + showcasing some tricks to ditch the need for multithreading.

>>>> example code here <<<<

  • added WebElement.click_safe() method, which you can try in case you get detected after clicking a link. This is not guaranteed t o work.

  • added WebElement.children(self, tag=None, recursive=False) to easily get/find child nodes. example:

    body = driver.find_element('tag name', 'body')
    
    # get the 6th child (any tag) of body, and grab all img's within (recursive). 
    images = body.children()[6].children('img', True)
    srcs = list(map(lambda _:_.attrs.get('src'), images))
    
  • added example.py where i can point people at when asking silly questions (no, its actually quite cool, everyone should see it)

  • added support for lambda platform

  • added support for x86_32

  • added support for systems reporting as linux2

  • some refactoring

3.1.6

still passing strong

  • use_subprocess now defaults to True. too many people don't understand multiprocessing and name == 'main, and after testing, it seems not to make a difference anymore in chrome 104+

  • added no_sandbox, which defaults to True, and this without the annoying "you are using unsecure command line ..." bar.

  • update Docker image. you can now vnc or rdp into your container to see the actual browser window demo

  • of course, "regular" mode works as well demo

3.1.0

this version might break your code, test before update!

  • added new anti-detection logic!

  • v2 has become the main module, so no need for references to v2 anymore. this mean you can now simply use:

    import undetected_chromedriver as uc driver = uc.Chrome() driver.get('https://nowsecure.nl')

    for backwards compatibility, v2 is not removed, but aliassed to the main module.

  • Fixed "welcome screen" nagging on non-windows OS-es. For those nagfetishists who ❤ welcome screens and feeding google with even more data, use Chrome(suppress_welcome=False).

  • replaced executable_path in constructor in favor of browser_executable_path which should not be used unless you are the edge case (yep, you are) who can't add your custom chrome installation folder to your PATH environment variable, or have an army of different browsers/versions and automatic lookup returns the wrong browser

  • "v1" (?) moved to _compat for now.

  • fixed dependency versions

  • ChromeOptions custom handling removed, so it is compatible with webdriver.chromium.options.ChromiumOptions.

  • removed Chrome.get() fu and restored back to "almost" original:

    • no with statements needed anymore, although it will still work for the sake of backward-compatibility.
    • no sleeps, stop-start-sessions, delays, or async cdp black magic!
    • this will solve a lot of other "issues" as well.
  • test success to date: 100%

  • just to mention it another time, since some people have hard time reading: headless is still WIP. Raising issues is needless

3.0.4 changes

  • change process creation behavior to be fully detached

  • changed .get(url) method to always use the contextmanager

  • changed .get(url) method to use cdp under the hood.

    ... the with statement is not necessary anymore ..

  • todo: work towards asyncification and selenium 4

words of wisdom:

Whenever you encounter the daunted

from session not created: This version of ChromeDriver only supports Chrome version 96 # or what ever version

the solution is simple:

import undetected_chromedriver as uc driver = uc.Chrome( version_main = 95 )

July 2021: Currently busy implementing selenium 4 for undetected-chromedriver

newsflash: https://github.com/ultrafunkamsterdam/undetected-chromedriver/pull/255

Usage

To prevent unnecessary hair-pulling and issue-raising, please mind the important note at the end of this document .

<br>

easy

Literally, this is all you have to do. Settings are included and your browser executable is found automagically. This is also the snippet i recommend using in case you experience an issue.

import undetected_chromedriver as uc driver = uc.Chrome() driver.get( 'https://nowsecure.nl' ) # my own test test site with max anti-bot protection

more advanced way, including setting profie folder

Literally, this is all you have to do. If a specified folder does not exist, a NEW profile is created. Data dirs which are specified like this will not be autoremoved on exit.

import undetected_chromedriver as uc options = uc.ChromeOptions() # setting profile options.user_data_dir = "c:\\temp\\profile" # use specific (older) version driver = uc.Chrome( options = options , version_main = 94 ) # version_main allows to specify your chrome version instead of following chrome global version driver.get( 'https://nowsecure.nl' ) # my own test test site with max anti-bot protection

expert mode, including Devtool/Wire events

Literally, this is all you have to do. You can now listen and subscribe to the low level devtools-protocol. I just recently found out that is also on planning for future release of the official chromedriver. However i implemented my own for now. Since i needed it myself for investigation.

import undetected_chromedriver as uc from pprint import pformat driver = uc.Chrome(enable_cdp_events=True) def mylousyprintfunction(eventdata): print(pformat(eventdata)) # set the callback to Network.dataReceived to print (yeah not much original) driver.add_cdp_listener("Network.dataReceived", mylousyprintfunction) driver.get('https://nowsecure.nl') # known url using cloudflare's "under attack mode" def mylousyprintfunction(message): print(pformat(message)) # for more inspiration checkout the link below # https://chromedevtools.github.io/devtools-protocol/1-3/Network/ # and of couse 2 lousy examples driver.add_cdp_listener('Network.requestWillBeSent', mylousyprintfunction) driver.add_cdp_listener('Network.dataReceived', mylousyprintfunction) # hint: a wildcard captures all events! # driver.add_cdp_listener('*', mylousyprintfunction) # now all these events will be printed in my console driver.get('https://nowsecure.nl') {'method': 'Network.requestWillBeSent', 'params': {'documentURL': 'https://nowsecure.nl/', 'frameId': 'F42BAE4BDD4E428EE2503CB5A7B4F700', 'hasUserGesture': False, 'initiator': {'type': 'other'}, 'loaderId': '449906A5C736D819123288133F2797E6', 'request': {'headers': {'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT ' '10.0; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, ' 'like Gecko) ' 'Chrome/90.0.4430.212 ' 'Safari/537.36', 'sec-ch-ua': '" Not A;Brand";v="99", ' '"Chromium";v="90", "Google ' 'Chrome";v="90"', 'sec-ch-ua-mobile': '?0'}, 'initialPriority': 'VeryHigh', 'method': 'GET', 'mixedContentType': 'none', 'referrerPolicy': 'strict-origin-when-cross-origin', 'url': 'https://nowsecure.nl/'}, 'requestId': '449906A5C736D819123288133F2797E6', 'timestamp': 190010.996717, 'type': 'Document', 'wallTime': 1621835932.112026}} {'method': 'Network.requestWillBeSentExtraInfo', 'params': {'associatedCookies': [], 'headers': {':authority': 'nowsecure.nl', ':method': 'GET', ':path': '/', ':scheme': 'https', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'sec-ch-ua': '" Not A;Brand";v="99", ' '"Chromium";v="90", "Google ' 'Chrome";v="90"', 'sec-ch-ua-mobile': '?0', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none', 'sec-fetch-user': '?1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; ' 'x64) AppleWebKit/537.36 (KHTML, like ' 'Gecko) Chrome/90.0.4430.212 ' 'Safari/537.36'}, 'requestId': '449906A5C736D819123288133F2797E6'}} {'method': 'Network.responseReceivedExtraInfo', 'params': {'blockedCookies': [], 'headers': {'alt-svc': 'h3-27=":443"; ma=86400, h3-28=":443"; ' 'ma=86400, h3-29=":443"; ma=86400', 'cache-control': 'private, max-age=0, no-store, ' 'no-cache, must-revalidate, ' 'post-check=0, pre-check=0', 'cf-ray': '65444b779ae6546f-LHR', 'cf-request-id': '0a3e8d7eba0000546ffd3fa000000001', 'content-type': 'text/html; charset=UTF-8', 'date': 'Mon, 24 May 2021 05:58:53 GMT', 'expect-ct': 'max-age=604800, ' 'report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'expires': 'Thu, 01 Jan 1970 00:00:01 GMT', 'nel': '{"report_to":"cf-nel","max_age":604800}', 'permissions-policy': 'accelerometer=(),autoplay=(),camera=(),clipboard-read=(),clipboard-write=(),fullscreen=(),geolocation=(),gyroscope=(),hid=(),interest-cohort=(),magnetometer=(),microphone=(),payment=(),publickey-credentials-get=(),screen-wake-lock=(),serial=(),sync-xhr=(),usb=()', 'report-to': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report?s=CAfobYlmWImQ90e%2B4BFBhpPYL%2FyGyBvkcWAj%2B%2FVOLoEq0NVrD5jU9m5pi%2BKI%2BOAnINLPXOCoX2psLphA5Z38aZzWNr3eW%2BDTIK%2FQidc%3D"}],"group":"cf-nel","max_age":604800}', 'server': 'cloudflare', 'vary': 'Accept-Encoding', 'x-frame-options': 'SAMEORIGIN'}, 'requestId': '449906A5C736D819123288133F2797E6', 'resourceIPAddressSpace': 'Public'}} {'method': 'Network.responseReceived', 'params': {'frameId': 'F42BAE4BDD4E428EE2503CB5A7B4F700', 'loaderId': '449906A5C736D819123288133F2797E6', 'requestId': '449906A5C736D819123288133F2797E6', 'response': {'connectionId': 158, 'connectionReused': False, 'encodedDataLength': 851,

编辑推荐精选

问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多