Package: cloudscraper
cloudscraperA simple Python module to bypass Cloudflare's anti-bot page (also known as "I'm Under Attack Mode", or IUAM), implemented withRequests. Cloudflare changes their techniques periodically, so I will update this repo frequently.This can be useful if you wish to scrape or crawl a website protected with Cloudflare. Cloudflare's anti-bot page currently just checks if the client supports Javascript, though they may add additional techniques in the future.Due to Cloudflare continually changing and hardening their protection page, cloudscraper requires a JavaScript Engine/interpreter to solve Javascript challenges. This allows the script to easily impersonate a regular web browser without explicitly deobfuscating and parsing Cloudflare's Javascript.For reference, this is the default message Cloudflare uses for these sorts of pages:Checking your browser before accessing website.com.

This process is automatic. Your browser will redirect to your requested content shortly.

Please allow up to 5 seconds...Any script using cloudscraper will sleep for ~5 seconds for the first visit to any site with Cloudflare anti-bots enabled, though no delay will occur after the first request.DonationsIf you feel like showing your love and/or appreciation for this project, then how about shouting me a coffee or beer :)InstallationSimply runpip install cloudscraper. The PyPI package is athttps://pypi.python.org/pypi/cloudscraper/Alternatively, clone this repository and runpython setup.py install.DependenciesPython 3.xRequests>= 2.9.2requests_toolbelt>= 0.9.1python setup.py installwill install the Python dependencies automatically. The javascript interpreters and/or engines you decide to use are the only things you need to install yourself, excluding js2py which is part of the requirements as the default.Javascript Interpreters and EnginesWe support the following Javascript interpreters/engines.ChakraCore:Library binaries can also be locatedhere.js2py:>=0.67native: Self made native python solver(Default)Node.jsV8:We use Sony'sv8eval() python module.UsageThe simplest way to use cloudscraper is by callingcreate_scraper().importcloudscraperscraper=cloudscraper.create_scraper()# returns a CloudScraper instance# Or: scraper = cloudscraper.CloudScraper()  # CloudScraper inherits from requests.Sessionprint(scraper.get("http://somesite.com").text)# => "<!DOCTYPE html><html><head>..."That's it...Any requests made from this session object to websites protected by Cloudflare anti-bot will be handled automatically. Websites not using Cloudflare will be treated normally. You don't need to configure or call anything further, and you can effectively treat all websites as if they're not protected with anything.You use cloudscraper exactly the same way you use Requests.cloudScraperworks identically to a RequestsSessionobject, just instead of callingrequests.get()orrequests.post(), you callscraper.get()orscraper.post().ConsultRequests' documentationfor more information.OptionsDisable Cloudflare V1DescriptionIf you don't want to even attempt Cloudflare v1 (Deprecated) solving..ParametersParameterValueDefaultdisableCloudflareV1(boolean)FalseExamplescraper=cloudscraper.create_scraper(disableCloudflareV1=True)BrotliDescriptionBrotlidecompression support has been added, and it is enabled by default.ParametersParameterValueDefaultallow_brotli(boolean)TrueExamplescraper=cloudscraper.create_scraper(allow_brotli=False)Browser / User-Agent FilteringDescriptionControl how and which User-Agent is "randomly" selected.ParametersCan be passed as an argument tocreate_scraper(),get_tokens(),get_cookie_string().ParameterValueDefaultbrowser(string)chromeorfirefoxNoneOrParameterValueDefaultbrowser(dict)browserdictParametersParameterValueDefaultbrowser(string)chromeorfirefoxNonemobile(boolean)Truedesktop(boolean)Trueplatform(string)'linux', 'windows', 'darwin', 'android', 'ios'Nonecustom(string)NoneExamplescraper=cloudscraper.create_scraper(browser='chrome')or# will give you only mobile chrome User-Agents on Androidscraper=cloudscraper.create_scraper(browser={'browser':'chrome','platform':'android','desktop':False})# will give you only desktop firefox User-Agents on Windowsscraper=cloudscraper.create_scraper(browser={'browser':'firefox','platform':'windows','mobile':False})# Custom will also try find the user-agent string in the browsers.json,# If a match is found, it will use the headers and cipherSuite from that "browser",# Otherwise a generic set of headers and cipherSuite will be used.scraper=cloudscraper.create_scraper(browser={'custom':'ScraperBot/1.0',})DebugDescriptionPrints out header and content information of the request for debugging.ParametersCan be set as an attribute via yourcloudscraperobject or passed as an argument tocreate_scraper(),get_tokens(),get_cookie_string().ParameterValueDefaultdebug(boolean)FalseExamplescraper=cloudscraper.create_scraper(debug=True)DelaysDescriptionCloudflare IUAM challenge requires the browser to wait ~5 seconds before submitting the challenge answer, If you would like to override this delay.ParametersCan be set as an attribute via yourcloudscraperobject or passed as an argument tocreate_scraper(),get_tokens(),get_cookie_string().ParameterValueDefaultdelay(float)extracted from IUAM pageExamplescraper=cloudscraper.create_scraper(delay=10)Existing sessionDescription:If you already have an existing Requests session, you can pass it to the functioncreate_scraper()to continue using that session.ParametersParameterValueDefaultsess(requests.session)NoneExamplesession=requests.session()scraper=cloudscraper.create_scraper(sess=session)NoteUnfortunately, not all of Requests session attributes are easily transferable, so if you run into problems with this,You should replace your initial session initialization callFrom:sess=requests.session()To:sess=cloudscraper.create_scraper()JavaScript Engines and InterpretersDescriptioncloudscraper currently supports the following JavaScript Engines/InterpretersChakraCorejs2pynative: Self made native python solver(Default)Node.jsV8ParametersCan be set as an attribute via yourcloudscraperobject or passed as an argument tocreate_scraper(),get_tokens(),get_cookie_string().ParameterValueDefaultinterpreter(string)nativeExamplescraper=cloudscraper.create_scraper(interpreter='nodejs')3rd Party Captcha SolversDescriptioncloudscrapercurrently supports the following 3rd party Captcha solvers, should you require them.2captchaanticaptchaCapSolverCapMonster Clouddeathbycaptcha9kwreturn_responseNoteI am working on adding more 3rd party solvers, if you wish to have a service added that is not currently supported, please raise a support ticket on github.Required ParametersCan be set as an attribute via yourcloudscraperobject or passed as an argument tocreate_scraper(),get_tokens(),get_cookie_string().ParameterValueDefaultcaptcha(dict)None2captchaRequiredcaptchaParametersParameterValueRequiredDefaultprovider(string)2captchayesapi_key(string)yesno_proxy(boolean)noFalseNoteif proxies are set you can disable sending the proxies to 2captcha by settingno_proxytoTrueExamplescraper=cloudscraper.create_scraper(captcha={'provider':'2captcha','api_key':'your_2captcha_api_key'})anticaptchaRequiredcaptchaParametersParameterValueRequiredDefaultprovider(string)anticaptchayesapi_key(string)yesno_proxy(boolean)noFalseNoteif proxies are set you can disable sending the proxies to anticaptcha by settingno_proxytoTrueExamplescraper=cloudscraper.create_scraper(captcha={'provider':'anticaptcha','api_key':'your_anticaptcha_api_key'})CapSolverRequiredcaptchaParametersParameterValueRequiredDefaultprovider(string)captchaaiyesapi_key(string)yesExamplescraper=cloudscraper.create_scraper(captcha={'provider':'capsolver','api_key':'your_captchaai_api_key'})CapMonster CloudRequiredcaptchaParametersParameterValueRequiredDefaultprovider(string)capmonsteryesclientKey(string)yesno_proxy(boolean)noFalseNoteif proxies are set you can disable sending the proxies to CapMonster by settingno_proxytoTrueExamplescraper=cloudscraper.create_scraper(captcha={'provider':'capmonster','clientKey':'your_capmonster_clientKey'})deathbycaptchaRequiredcaptchaParametersParameterValueRequiredDefaultprovider(string)deathbycaptchayesusername(string)yespassword(string)yesExamplescraper=cloudscraper.create_scraper(captcha={'provider':'deathbycaptcha','username':'your_deathbycaptcha_username','password':'your_deathbycaptcha_password',})9kwRequiredcaptchaParametersParameterValueRequiredDefaultprovider(string)9kwyesapi_key(string)yesmaxtimeout(int)no180Examplescraper=cloudscraper.create_scraper(captcha={'provider':'9kw','api_key':'your_9kw_api_key','maxtimeout':300})return_responseUse this if you want the requests response payload without solving the Captcha.RequiredcaptchaParametersParameterValueRequiredDefaultprovider(string)return_responseyesExamplescraper=cloudscraper.create_scraper(captcha={'provider':'return_response'})IntegrationIt's easy to integratecloudscraperwith other applications and tools. Cloudflare uses two cookies as tokens: one to verify you made it past their challenge page and one to track your session. To bypass the challenge page, simply include both of these cookies (with the appropriate user-agent) in all HTTP requests you make.To retrieve just the cookies (as a dictionary), usecloudscraper.get_tokens(). To retrieve them as a fullCookieHTTP header, usecloudscraper.get_cookie_string().get_tokensandget_cookie_stringboth accept Requests' usual keyword arguments (likeget_tokens(url, proxies={"http": "socks5://localhost:9050"})).Please readRequests' documentation on request argumentsfor more information.User-Agent HandlingThe two integration functions return a tuple of(cookie, user_agent_string).You must use the same user-agent string for obtaining tokens and for making requests with those tokens, otherwise Cloudflare will flag you as a bot.That means you have to pass the returneduser_agent_stringto whatever script, tool, or service you are passing the tokens to (e.g. curl, or a specialized scraping tool), and it must use that passed user-agent when it makes HTTP requests.Integration examplesRemember, you must always use the same user-agent when retrieving or using these cookies. These functions all return a tuple of(cookie_dict, user_agent_string).Retrieving a cookie dict through a proxyget_tokensis a convenience function for returning a Python dict containing Cloudflare's session cookies. For demonstration, we will configure this request to use a proxy. (Please note that if you request Cloudflare clearance tokens through a proxy, you must always use the same proxy when those tokens are passed to the server. Cloudflare requires that the challenge-solving IP and the visitor IP stay the same.)If you do not wish to use a proxy, just don't pass theproxieskeyword argument. These convenience functions support all of Requests' normal keyword arguments, likeparams,data, andheaders.importcloudscraperproxies={"http":"http://localhost:8080","https":"http://localhost:8080"}tokens,user_agent=cloudscraper.get_tokens("http://somesite.com",proxies=proxies)print(tokens)# => {'cf_clearance':'c8f913c707b818b47aa328d81cab57c349b1eee5-1426733163-3600','__cfduid':'dd8ec03dfdbcb8c2ea63e920f1335c1001426733158'}Retrieving a cookie stringget_cookie_stringis a convenience function for returning the tokens as a string for use as aCookieHTTP header value.This is useful when crafting an HTTP request manually, or working with an external application or library that passes on raw cookie headers.importcloudscrapercookie_value,user_agent=cloudscraper.get_cookie_string('http://somesite.com')print('GET / HTTP/1.1\nCookie:{}\nUser-Agent:{}\n'.format(cookie_value,user_agent))# GET / HTTP/1.1# Cookie: cf_clearance=c8f913c707b818b47aa328d81cab57c349b1eee5-1426733163-3600; __cfduid=dd8ec03dfdbcb8c2ea63e920f1335c1001426733158# User-Agent: Some/User-Agent Stringcurl exampleHere is an example of integrating cloudscraper with curl. As you can see, all you have to do is pass the cookies and user-agent to curl.importsubprocessimportcloudscraper# With get_tokens() cookie dict:# tokens, user_agent = cloudscraper.get_tokens("http://somesite.com")# cookie_arg = 'cf_clearance={}; __cfduid={}'.format(tokens['cf_clearance'], tokens['__cfduid'])# With get_cookie_string() cookie header; recommended for curl and similar external applications:cookie_arg,user_agent=cloudscraper.get_cookie_string('http://somesite.com')# With a custom user-agent string you can optionally provide:# ua = "Scraping Bot"# cookie_arg, user_agent = cloudscraper.get_cookie_string("http://somesite.com", user_agent=ua)result=subprocess.check_output(['curl','--cookie',cookie_arg,'-A',user_agent,'http://somesite.com'])Trimmed down version. Prints page contents of any site protected with Cloudflare, via curl.Warning:shell=Truecan be dangerous to use withsubprocessin real code.url="http://somesite.com"cookie_arg,user_agent=cloudscraper.get_cookie_string(url)cmd="curl --cookie{cookie_arg}-A{user_agent}{url}"print(subprocess.check_output(cmd.format(cookie_arg=cookie_arg,user_agent=user_agent,url=url),shell=True))CryptographyDescriptionControl communication between client and serverParametersCan be passed as an argument tocreate_scraper().ParameterValueDefaultcipherSuite(string)NoneecdhCurve(string)prime256v1server_hostname(string)NoneExample# Some servers require the use of a more complex ecdh curve than the default "prime256v1"# It may can solve handshake failurescraper=cloudscraper.create_scraper(ecdhCurve='secp384r1')# Manipulate server_hostnamescraper=cloudscraper.create_scraper(server_hostname='www.somesite.com')scraper.get('https://backend.hosting.com/',headers={'Host':'www.somesite.com'})