Code Monkey home page Code Monkey logo

cloudscraper's Introduction

πŸ›‘ THIS LIBRARY IS NO LONGER SUPPORTED AND IS DEPRECATED πŸ›‘

cloudscraper

Node.js library to bypass Cloudflare's anti-ddos page.

js-semistandard-style

Build status Coverage Dependency Status Greenkeeper badge

If the page you want to access is protected by Cloudflare, it will return special page, which expects client to support Javascript to solve challenge.

This small library encapsulates logic which extracts challenge, solves it, submits and returns the request page body.

You can use cloudscraper even if you are not sure if Cloudflare protection is turned on.

In general, Cloudflare has 4 types of common anti-bot pages:

  • Simple html+javascript page with challenge
  • Page which redirects to original site
  • Page with reCAPTCHA
  • Page with error ( your ip was banned, etc)

If you notice that for some reason cloudscraper stops working, do not hesitate and get in touch with me ( by creating an issue here, for example), so i can update it.

Install

npm install cloudscraper

Saving the request module as a dependency is compulsory.

# Pin the request version
npm install --save request

Support for Brotli encoded responses is enabled by default when using Node.js v10 or later. If you wish to enable support for older Node.js versions, you may install brotli. It is recommended but not required.

Usage

Cloudscraper uses request-promise by default since v3. You can find the migration guide here.

var cloudscraper = require('cloudscraper');

cloudscraper.get('https://website.com/').then(console.log, console.error);

or for POST action:

var options = {
  uri: 'https://website.com/',
  formData: { field1: 'value', field2: 2 }
};

cloudscraper.post(options).then(console.log).catch(console.error);

Examples live in the docs directory of the Github repo and can be found here.

A generic request can be made with cloudscraper(options). The options object should follow request's options. Not everything is supported however, for example http methods other than GET and POST. If you wanted to request an image in binary data you could use the encoding option:

var options = {
  method: 'GET',
  url:'http://website.com/',
};

cloudscraper(options).then(console.log);

Advanced usage

Cloudscraper allows you to specify your own requester, one of either request or request-promise. Cloudscraper wraps the requester and accepts the same options, so using cloudscraper is pretty much like using those two libraries.

  • Cloudscraper exposes the same HTTP verb methods as request:
    • cloudscraper.get(options, callback)
    • cloudscraper.post(options, callback)
    • cloudscraper(uri)
  • Cloudscraper uses request-promise by default, promise chaining is done exactly the same as described in docs:
 cloudscraper(options)
   .then(function (htmlString) {
   })
   .catch(function (err) {
   });

Please refer to the requester's documentation for further instructions.

Sucuri

Cloudscraper can also identify and automatically bypass Sucuri WAF. No actions are required.

ReCAPTCHA

Cloudscraper may help you with the reCAPTCHA page. Take a look at this example and an example using promises.

Cloudflare may send a reCAPTCHA depending on the negotiated TLS cipher suite and extensions. Reducing the default cipher suite to only ciphers supported by Cloudflare may mitigate the problem: https://developers.cloudflare.com/ssl/ssl-tls/cipher-suites/

Only specifying the Cloudflare preferred TLSv1.2 cipher is also an option:

var cloudscraper = require('cloudscraper').defaults({
  agentOptions: {
    ciphers: 'ECDHE-ECDSA-AES128-GCM-SHA256'
  }
})

More information on TLS issues can be found here.

Defaults method

cloudscraper.defaults is a very convenient way of extending the cloudscraper requests with any of your settings.

var cloudscraper = require('cloudscraper').defaults({ 'proxy': 'http://localproxy.com' });
// Overriding headers to remove them or using uncommon headers will cause reCAPTCHA responses
var headers = { /* ... */ };
var cloudscraper = require('cloudscraper').defaults({ headers: headers });

cloudscraper(options).then(console.log);

Configuration

Cloudscraper exposes the following options that are required by default but might be changed. Please note that the default values eliminate the chance of getting sent a CAPTCHA.

var options = {
  uri: 'https://website',
  jar: requestModule.jar(), // Custom cookie jar
  headers: {
    // User agent, Cache Control and Accept headers are required
    // User agent is populated by a random UA.
    'User-Agent': 'Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36',
    'Cache-Control': 'private',
    'Accept': 'application/xml,application/xhtml+xml,text/html;q=0.9, text/plain;q=0.8,image/png,*/*;q=0.5'
  },
  // Cloudscraper automatically parses out timeout required by Cloudflare.
  // Override cloudflareTimeout to adjust it.
  cloudflareTimeout: 5000,
  // Reduce Cloudflare's timeout to cloudflareMaxTimeout if it is excessive
  cloudflareMaxTimeout: 30000,
  // followAllRedirects - follow non-GET HTTP 3xx responses as redirects
  followAllRedirects: true,
  // Support only this max challenges in row. If CF returns more, throw an error
  challengesToSolve: 3,
  // Remove Cloudflare's email protection, replace encoded email with decoded versions
  decodeEmails: false,
  // Support gzip encoded responses (Should be enabled unless using custom headers)
  gzip: true,
  // Removes a few problematic TLSv1.0 ciphers to avoid CAPTCHA
  agentOptions: { ciphers }
};

cloudscraper(options).then(console.log);

You can access the default configuration with cloudscraper.defaultParams

Error object

Cloudscraper error object inherits from Error has following fields:

  • name - RequestError/CaptchaError/CloudflareError/ParserError
  • options - The request options
  • cause - An alias for error
  • response - The request response
  • errorType - Custom error code Where errorType can be following:
  • 0 if request to page failed due to some native reason as bad url, http connection or so. error in this case will be error event
  • 1 Cloudflare returned CAPTCHA. Nothing to do here. Bad luck
  • 2 Cloudflare returned page with some inner error. error will be Number within this range 1012, 1011, 1002, 1000, 1004, 1010, 1006, 1007, 1008. See more here
  • 3 this error is returned when library failed to parse and solve js challenge. error will be String with some details. ⚠️ ⚠️ Most likely it means that Cloudflare have changed their js challenge.
  • 4 CF went into a loop and started to return challenge after challenge. If number of solved challenges is greater than 3 and another challenge is returned, throw an error

Errors are descriptive. You can find a list of all known errors here.

Do not always rely on error.cause to be an error, it can be a string.

Running tests

Clone this repo, do npm install and then just npm test

Unknown error? Library stopped working?

Let me know, by opening an issue in this repo and I will update library asap. Please, provide url and body of page where cloudscraper failed.

WAT

Current Cloudflare implementation requires browser to respect the timeout of 5 seconds and cloudscraper mimics this behaviour. So everytime you call cloudscraper.get/post you should expect it to return result after minimum 6 seconds. If you want to change this behaviour, you would need to make a generic request as described in above and pass cloudflareTimeout options with your value. But be aware that Cloudflare might track this timeout and use it against you ;)

TODO

  • Check for reCAPTCHA
  • Support cookies, so challenge can be solved once per session
  • Support page with simple redirects
  • Add proper testing
  • Remove manual 302 processing, replace with followAllRedirects param
  • Parse out the timeout from challenge page
  • Reorder the arguments in get/post/request methods and allow custom options to be passed in
  • Support reCAPTCHA solving
  • Promisification

Kudos to contributors

In the beginning cloudscraper was a port of python module cloudflare-scrape. Thank you Anorov for an inspiration.

Dependencies

cloudscraper's People

Contributors

askmike avatar bryant1410 avatar buro9 avatar codemanki avatar colecf avatar greenkeeper[bot] avatar jngbng avatar kevinvanrijn avatar lgaticaq avatar roflmuffin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cloudscraper's Issues

There is a better way to extend request

This library really should extend request the same way that request-promise does. It'd probably close all of the currently open issues. I'll work on a bit later but here is the gist of it.

The example below shows how to support request and request-promise. Simply have them both as peer dependencies (not installed automatically) and users can continue to use request as they normally would.

  • Edited to show option handling

I'll update to show response handling but I think it's all pretty straight forward if you look at the code for request and request-promise.

// Snippet removed (See edit history or referenced PR)

Umlaute Problem

cloudscraper.post("/api", {
  location: "Γ–sterreich",
  ip: "192.168.0.12",
});

But it shows on Server Side

{ location: "Γ–sterreich",
  ip: '192.168.0.1' }

How to use with casperJS

I am going to crawl a webpage which I use casperJS, how can I use the cloudscraper to bypass the cloudfare challenge with casperjs, any example?

Unable to scrape kissanime.com

Problem

I'm having subsequent failures when requesting to kissanime.com. Running this code gives me a null error but a CloudFlare page

Output

--------------
ERROR
--------------
null

--------------
BODY
--------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Please wait 5 seconds...</title>
<script type="text/javascript">
  //<![CDATA[
  (function(){
    var a = function() {try{return !!window.addEventListener} catch(e) {return !1} },
    b = function(b, c) {a() ? document.addEventListener("DOMContentLoaded", b, c) : document.attachEvent("onreadystatechange", b)};
    b(function(){
      var a = document.getElementById('cf-content');a.style.display = 'block';
      setTimeout(function(){
        var s,t,o,p,b,r,e,a,k,i,n,g,f, JIpeumZ={"TKWvJSqmT":+((!+[]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]))};
        t = document.createElement('div');
        t.innerHTML="<a href='/'>x</a>";
        t = t.firstChild.href;r = t.match(/https?:\/\//)[0];
        t = t.substr(r.length); t = t.substr(0,t.length-1);
        a = document.getElementById('jschl-answer');
        f = document.getElementById('challenge-form');
        ;JIpeumZ.TKWvJSqmT+=+((!+[]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));JIpeumZ.TKWvJSqmT*=+((!+[]+!![]+[])+(+[]));JIpeumZ.TKWvJSqmT-=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]));JIpeumZ.TKWvJSqmT*=+((!+[]+!![]+!![]+[])+(+[]));a.value = parseInt(JIpeumZ.TKWvJSqmT, 10) + t.length; '; 121'
        f.submit();
      }, 4000);
    }, false);
  })();
  //]]>
</script>

</head>
<body>
<div>
<div style="position: relative; height: 130px;">
<div style="max-width: 635px; margin: 0 auto; z-index: 1000; text-align: center;
                position: relative; margin-top: 150px; width: 100%">
<img id="imgLogo" alt="jadopado" style="display: inline-block;" src="data:image/gif;charset=binary;base64,R0lGODlhZABkAPUaAPX19c/Pz+zs7Pr6+vHx8cXFxbe3t7KysuLi4srKysHBwdnZ2d3d3dTU1Ly8vOfn5/j4+Pz8/PLy8szMzN/f39z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PSj6SE57Ogggo4Bwn4K+fwLE7yMx7VQUj8ygkRBiKAeBNGAUPgpGExEBACH5BAUAAAEALBwAMwANAA0AAAU6YCAGG2Ru47hpV9sSqBg9bu3FXq0LAaD/A9avJhEMawLjsdUhLFscyPMSCXSWBNFGqdOkermWBzAKAQAh+QQFAAADACwcADMADQANAAAFOuAgDpFkRuMYUVPbIqgIBW5txVatL4Og/wDWr3ZZDGsL47FVQSxbGMlzAhlUlghRRKmjpHq5lkUwCgEAIfkEBQAADgAsHAAzAA0ADQAABDbQSTeEHXOOcHpvmAQYXqmESqkWDqK+BPeWSzGXhX13SbN3DMHvAHAkdg3JQKcKZFqpjgIxiQAAIfkEBQAAAQAsFQAjAA0ADQAABj3AgDBCEFwEGohwCbg4nxcCE0qVbh5UaqSZhRIkXagAHHaOy2YQ+sIJeMqPTWCA7YKWAyP0o1wKBxKBd0tBACH5BAUAAAMALBUAIwANAA0AAAU54CBCyDItlCSuwuS+E8LCtBwFNA21OYxcPdgCGHQNi0YNcoIZWIqByACA62lWABMso1qJAJfwdRUCACH5BAUAAAkALBUAIwANAA0AAAQ1MEnQyilByI2O/0fDgaQ4GCQJdCnYLC1YwLE31/aDH0yi1IZBgoBqPTYEC8ih2UgIi+hxEwEAIfkEBQAAAQAsHAASAA0ADQAABTtgIAYRIAHROEbC5brdNg7Paz9p8Nm8EAC8IKQT5ElaxZcAmbxoCE0XZxC9pKBJyUhTJKgCQ9ejAxmFAAA7"><br />
</div>
</div>
<div>
<div style="text-align: center">
Please wait 5 seconds...<br />Make sure to enable cookies and javascript.<br />This site does not work with "Mini browsers" (e.g. UC mini, Opera mini...)
</div>
<div style="margin: 0 auto; visibility: hidden">
<div class="cf-browser-verification cf-im-under-attack">
  <noscript><h1 data-translate="turn_on_js" style="color:#bd2426;">Please turn JavaScript on and reload the page.</h1></noscript>
  <div id="cf-content" style="display:none">
    <div>
      <div class="bubbles"></div>
      <div class="bubbles"></div>
      <div class="bubbles"></div>
    </div>
    <h1><span data-translate="checking_browser">Checking your browser before accessing</span> kissanime.to.</h1>
    <p data-translate="process_is_automatic">This process is automatic. Your browser will redirect to your requested content shortly.</p>
    <p data-translate="allow_5_secs">Please allow up to 5 seconds&hellip;</p>
  </div>
  <form id="challenge-form" action="/cdn-cgi/l/chk_jschl" method="get">
    <input type="hidden" name="jschl_vc" value="b5ef2df50c21a08804dd3238e6669288"/>
    <input type="hidden" name="pass" value="1480319486.85-CJpLFmT3Vp"/>
    <input type="hidden" id="jschl-answer" name="jschl_answer"/>


Init
  </form>
</div>

</div>
</div>
<div style="padding: 20px;">
</div>
</div>
</body>
</html>

Note

I'm not sure myself if CloudFlare is throttling me. I was able to get this library to work for a single time an hour ago, but never had any another success again. Will try again tonight if I can get this to work.

Proxy support

Hi, is there any way to implement proxies into this?

Solver not working anymore

Hi,
previously the CF challenge was extracted with the following function:
var challenge = body.match(/S='([^']+)'/);

Now they made that variable random and added a random-name property on it for the challenge. Full example:

<script type="text/javascript">
--
Β  | //<![CDATA[
Β  | (function(){
Β  | var a = function() {try{return !!window.addEventListener} catch(e) {return !1} },
Β  | b = function(b, c) {a() ? document.addEventListener("DOMContentLoaded", b, c) : document.attachEvent("onreadystatechange", b)};
Β  | b(function(){
Β  | var a = document.getElementById('cf-content');a.style.display = 'block';
Β  | setTimeout(function(){
Β  | var s,t,o,p,b,r,e,a,k,i,n,g,f, bUNLJBB={"xqYrWXXfBO":+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![]+!![])+(!+[]+!![]+!![]))/+((!+[]+!![]+[])+(!+[]+!![]+!![]+!![])+(!+[]+!![])+(+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(+[])+(+!![])+(!+[]+!![]))};
Β  | t = document.createElement('div');
Β  | t.innerHTML="<a href='/'>x</a>";
Β  | t = t.firstChild.href;r = t.match(/https?:\/\//)[0];
Β  | t = t.substr(r.length); t = t.substr(0,t.length-1);
Β  | a = document.getElementById('jschl-answer');
Β  | f = document.getElementById('challenge-form');
Β  | ;bUNLJBB.xqYrWXXfBO-=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]))/+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(+[])+(+[])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));bUNLJBB.xqYrWXXfBO+=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]+!![])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]))/+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![])+(+!![])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(+!![])+(!+[]+!![]+!![]+!![]));bUNLJBB.xqYrWXXfBO*=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]+!![])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]))/+((+!![]+[])+(+[])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(+!![]));bUNLJBB.xqYrWXXfBO*=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![]+!![])+(!+[]+!![]+!![]))/+((!+[]+!![]+!![]+!![]+!![]+[])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]));bUNLJBB.xqYrWXXfBO*=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![])+(+!![])+(+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+!![]))/+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(+!![])+(!+[]+!![]+!![]));bUNLJBB.xqYrWXXfBO-=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]))/+((!+[]+!![]+[])+(!+[]+!![]+!![])+(+[])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+!![])+(+!![])+(!+[]+!![]));bUNLJBB.xqYrWXXfBO*=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(+[])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]))/+((!+[]+!![]+[])+(+!![])+(!+[]+!![]+!![])+(!+[]+!![]+!![])+(!+[]+!![]+!![])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+!![])+(!+[]+!![]+!![]+!![]+!![]));bUNLJBB.xqYrWXXfBO*=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]+!![])+(+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![])+(+!![]))/+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(+!![])+(+[])+(+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));bUNLJBB.xqYrWXXfBO+=+((!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]))/+((!+[]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!+[]+!![]));a.value = +bUNLJBB.xqYrWXXfBO.toFixed(10) + t.length; '; 121'
Β  | f.action += location.hash;
Β  | f.submit();
Β  | }, 4000);
Β  | }, false);
Β  | })();
Β  | //]]>
Β  | </script>

In the above example the challenge comes from the variable var bUNLJBB.xqYrWXXfBO which returns a number. But as mentioned, the variable name is random

I can see this is possible to extract, but requires a lot more work. Has anybody been working on this already?

edit. I can see the extraction of the HTML form variables still works, and I do get past the CF challenge in some cases. However in some cases it fails, presumably due to the JavaScript above.

Issue with captcha

Hello,
I have an issue with cloudscraper, i get an error code 1, when i try to get a page from hltv.org.
But i can get the source without any problem when i just use request.
Any ideas ?

Thanks for your job

superagent make me crazy..orz..

i write a "cloudscraper" by superagent module, but not success. i think superagent cookie jar module have problem.
the same code, i change to use request module. it succeed.

i still not found the problem on superagent. crazy..

Re-use request

Re-using the request makes it possible to re-use the request agent (in some cases) and preserves header information that may be lost. This should be a non-breaking change. Request has smart option handling so it's quite easy to achieve this.

Consider the following code example.

requestModule('https://example.com', function(error, response, body) {
  var options = response.request;
  console.log(options.uri, options.headers, options.agent);
  options.uri = 'https://example.com/path';
  requestModule(options, callback);
});

Also, if we want to just reinitialize(redirect) the request, it would simplify the code base as you don't have to pass around the callback or options. You'd only need to pass the response object around. challengesToSolve could be entirely removed as request's redirect options can be used instead.

not following redirections

hi

everything is in the title

i added :

followAllRedirects: true

to all your performRequest functions and everything is right :)

(don t have time to fork / make PR now, sorry)

Possible to login into website?

Hi!

What I'm asking is, I'm making a small REST API for a website, and I was wondering, is it possible to do a POST to a login page, and save the session cookie to that website, and keep being logged in for the rest of the session?

Hope it makes sense!

where to get the cf_clearance cookie

I'm modifying the module to get the cf_clearance cookie, but the original web response doesn't have it, it have other cookies but not this one, which is the one needed to get the web without bypassing it again.

In which stage could i get this one?

allow streaming

if possible, can you expose the stream interface from request?

Stopped working, loads cloudflare html instead of file

Today I noticed that the scraper stopped working for me although it worked before.

This is the url that I tried to get: https://www.spigotmc.org/resources/5583/download?version=140619

Source:

cloudscraper.request({method: 'GET', url:url, encoding: null}, function(err, response, body) {});

And that's the body, while error is empty:

<!DOCTYPE html>
<html ng-app="downloadApp" ng-controller="parentController">
<head>
<title ng-bind="pageTitle">Download</title>
<script type="text/javascript">
//<![CDATA[
try{if (!window.CloudFlare) {var CloudFlare=[{verbose:0,p:0,byc:0,owlid:"cf",bag2:1,mirage2:0,oracle:0,paths:{cloudflare:"/cdn-cgi/nexp/dok3v=1613a3a185/"},atok:"452c95e5d0ef3672607ab953ca2cc8ae",petok:"4bd31b8e0a7167e6fb0beca53a8864b1d2371cd7-1487097634-1800",zone:"inventivetalent.org",rocket:"0",apps:{"ga_key":{"ua":"UA-43843691-3","ga_bs":"2"}}}];!function(a,b){a=document.createElement("script"),b=document.getElementsByTagName("script")[0],a.async=!0,a.src="//ajax.cloudflare.com/cdn-cgi/nexp/dok3v=f2befc48d1/cloudflare.min.js",b.parentNode.insertBefore(a,b)}()}}catch(e){};
//]]>
</script>
<link id="favicon" rel="shortcut icon" type="image/png" href="/favicon_full.png"/>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<meta name=viewport content="width=device-width, initial-scale=1">
<base href="/">
<style>.centered{position:fixed;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);}</style>
<script type="text/javascript">
/* <![CDATA[ */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-43843691-3']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

(function(b){(function(a){"__CF"in b&&"DJS"in b.__CF?b.__CF.DJS.push(a):"addEventListener"in b?b.addEventListener("load",a,!1):b.attachEvent("onload",a)})(function(){"FB"in b&&"Event"in FB&&"subscribe"in FB.Event&&(FB.Event.subscribe("edge.create",function(a){_gaq.push(["_trackSocial","facebook","like",a])}),FB.Event.subscribe("edge.remove",function(a){_gaq.push(["_trackSocial","facebook","unlike",a])}),FB.Event.subscribe("message.send",function(a){_gaq.push(["_trackSocial","facebook","send",a])}));"twttr"in b&&"events"in twttr&&"bind"in twttr.events&&twttr.events.bind("tweet",function(a){if(a){var b;if(a.target&&a.target.nodeName=="IFRAME")a:{if(a=a.target.src){a=a.split("#")[0].match(/[^?=&]+=([^&]*)?/g);b=0;for(var c;c=a[b];++b)if(c.indexOf("url")===0){b=unescape(c.split("=")[1]);break a}}b=void 0}_gaq.push(["_trackSocial","twitter","tweet",b])}})})})(window);
/* ]]> */
</script>
</head>
<body>
<div class="container">
<div ng-view>
<div class="centered">
<h1>Loading Download...</h1>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js" integrity="sha384-k+Qp/8rZxoiiYGVjOBiZwkEp5yv6clgl2EmwNaE1oUMlfmEYgCWazxf4CyxfZiWG" crossorigin="anonymous"></script>
<script src="js/script.js"></script>
</body>
</html>

Cannot read property 'toString' of undefined

When i'm using proxy for HTTPS requests after long time sometimes happen this:

node_modules/cloudscraper/index.js:201
    callback(error, response, body.toString(options.realEncoding));
                                  ^

TypeError: Cannot read property 'toString' of undefined
    at giveResults (node_modules/cloudscraper/index.js:201:35)
    at Request._callback (node_modules/cloudscraper/index.js:186:7)
    at self.callback (node_modules/request/request.js:200:22)
    at emitOne (events.js:77:13)
    at Request.emit (events.js:169:7)
    at Request.onRequestError (node_modules/request/request.js:831:8)
    at emitOne (events.js:77:13)
    at ClientRequest.emit (events.js:169:7)
    at Socket.socketErrorListener (_http_client.js:264:9)
    at emitOne (events.js:77:13)
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
process.env.HTTP_PROXY = 'http://138.0.172.145:80'; //this proxy sometimes works..

Doesn't provide actual body for website

Website is https://mcsniper.co/ - they have a custom cloudflare page which I believe may be the root cause of the issue.

Code snippet:

cloudscraper.request({
        method: "GET",
        url: "https://mcsniper.co/",
        proxy: "http://[REDACTED]",
        headers: {
            "User-Agent": "[REDACTED]",
        },
        timeout: (30 * 1000),
    }

Custom User Agent

Is there the possibility to specify the User Agent when made GET?
If no, can it be implemented?
Thanks

Email protection is not parsed by cloudscraper

On Crunchyroll, they have activated the "email protection" from cloudflare and when I try to scrape some of their webpages I get "[email protected]" instead of the expected text.

Example: http://www.crunchyroll.com/the-idolmster-cinderella-girls-theater#

On that webpage the "DOLM@STER" is seen as an email by cloudflare (that mean their regexp is fabulously wrong) and it screw my scraping because I'm not expecting ton of the javascript they insert for that "protection".

It would be nice if cloudscraper could detect these insertion and parse them the same as it does for the browser detection.

Thank you!

wow, wonderful! it help me so much! thanks!

No error, body returned is cloudflare challenge page.

I am having issues when trying to retrieve a website that is in "I'm under attack mode" (http://kissanime.com)

With a very basic cloudscraper.get, no error is returned however the body of the response is the Cloudflare challenge page.

I have noticed this is a sister site to the website currently being investigated in Issue #1, so that might hold some relevance?

Interesting thing to note is that this issue does not occur when using cloudflare-scraper

Support caching

Hi, I'm trying to cache the requests but sending the 'Cache-Control' header doesn't seem to have any effect. Here's the code:

cloudscraper.request(
			{
				method: "GET",
				url: link,
				encoding: null,
				headers: {
					"content-type": "image/jpeg",
					"Cache-Control": "max-age:31556926"
				}
			},

get Images

with the "Request" object, I could get images doing

    var requestSettings = {
        url: img_url,
        method: 'GET',
        encoding: null
    };    
    request.get(requestSettings, function (error, response, body) { ... });

I'd like to do the same with cloud scraper, otherwise it takes the file but it's not recognized as image (probably for the wrong encoding)

TypeError index.js:83

  makeRequest(options, function(error, response, body) {
    var validationError;
    var stringBody = body.toString('utf8');

    if (validationError = checkForErrors(error, stringBody)) {
      return callback(validationError, body, response);
    }

    // If body contains specified string, solve challenge
    if (stringBody.indexOf('a = document.getElementById(\'jschl-answer\');') !== -1) {
      setTimeout(function() {
        return solveChallenge(response, stringBody, options, callback);
      }, Timeout);
    } else {
      // All is good
      giveResults(options, error, response, body, callback);
    }
  });
}

function checkForErrors(error, body) {
  var match;

  // Pure request error (bad connection, wrong url, etc)
  if(error) {
    return { errorType: 0, error: error };
  }

  // Finding captcha
  if (body.indexOf('why_captcha') !== -1 || /recaptcha/i.test(body)) {
    return { errorType: 1 };
  }

  // trying to find '<span class="cf-error-code">1006</span>'
  match = body.match(/<\w+\s+class="cf-error-code">(.*)<\/\w+>/i);

  if (match) {
    return { errorType: 2, error: parseInt(match[1]) };
  }

  return false;
}

body.toString() is called unsafely. Some request errors cause body to be undefined.

Shared jar

Hi,

First of all: thanks for a great job! Saved me heaps of time :)
In my project, I need a persistent jar, so I have a small suggestion.

In the first couple of lines, you create a private jar. How about changing this slightly:
var defaultJar = requestModule.jar();
var request = requestModule.defaults({jar: defaultJar}), // Cookies should be enabled

Then, as the first line in function setCookieAndReload:
var jar = options.jar || defaultJar;

It now uses the (shared) jar from the options, or - if that is not provided - the default (private) jar.
Works like a charm!

Thanks again,
Goswinus

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.