10 tips to avoid getting Blocked while Scraping Websites
Data Scraping is something that has to be done quite responsibly. You have to be very cautious about the website you are scraping. It could have negative effects on the website. There are FREE web scrapers in the market which can smoothly scrape any website without getting blocked. Many websites on the web do not have any anti-scraping mechanism but some of the websites do block scrapers because they do not believe in open data access. One
the thing you have to keep in mind is BE NICE and FOLLOW SCRAPING POLICIES of the website
But if you are building web scrapers for your project or a company then you must follow these 10 tips before even starting to scrape any website.
1. ROBOTS.TXT
First of all, you have to understand what is robots.txt file and what is its functionality. So, basically it tells search engine crawlers which pages or files the crawler can or can't request from your site. This is used mainly to avoid Overloading any website with requests. This file provides standard rules about scraping. Many websites allow GOOGLE to let them scrape their websites. One can find robots.txt file on websites — http://example.com/robots.txt.Sometimes certain websites have User-agent: * or Disallow: / in their robots.txt file which means they don't want you to scrape their websites.Basically anti-scraping mechanism works on a fundamental rule which is: Is it a bot or a human? For analyzing this rule it has to follow certain criteria in order to make a decision.
Points referred by an anti-scraping mechanism:
If you are scraping pages faster than a human possibly can, you will fall into a category called “bots”.
Following the same pattern while scraping. Like for example, you are going through every page of That target domain for just collecting images or links. If you are scraping using the same IP for a certain period of time. User Agent missing. Maybe you are using a headerless browser like Tor Browser
If you keep these points in mind while scraping a website, I am pretty sure you will be able to scrape any website on the web.
2. IP Rotation
This is the easiest way for anti-scraping mechanisms to caught you red-handed.If you keep using the same IP for every request you will be blocked.So, for every successful scraping request, you must use a new IP For Every Request. You Must Have A Pool Of At Least 10 IPs Before Making An HTTP Request. To Avoid Getting Blocked You Can Use Proxy Rotating Services Like Scrapingdog Or Any Other Proxy Services . I Am Putting A Small Python Code Snippet Which Can Be Used to create a pool of new IP address before making a
request.
from bs4 import BeautifulSoup import requests
l = {}
u = list ()
url = ”https://www.proxynova.com/proxy-server-list/country-" + country_code + "/ "
respo = requests.get (url) .text
soup = BeautifulSoup (respo, 'html.parser')
allproxy = soup.find_all (“tr”)
for proxy in allproxy:
foo = proxy.find_all (“td”)
try:
l [“ip”] = foo [0] .text.replace (“\ n”, ”” ) .replace (“document.write (“, ””). replace (“)”, ””). replace (“\ '”, ””). replace (“;”, ””)
except:
l [“ ip ”] = None
try:
l [“ port ”] = foo [1] .text.replace (“ \ n ”,” ”). replace (“ “,” ”)
except:
l [“ port ”] = None
try:
l [“country”] = foo [5] .text.replace (“\ n”, ””). replace (““, ””)
except:
l [“country”] = None
if (l [“ port ”] is not None):
u.append (l)
l = {}
print (u)
This will provide you a JSON response with three properties which are IP, port, and country. This proxy API will provide IPs according to a country code.you can find country code here.
But for websites which have advanced bot detection mechanism, you have to use either mobile or residential proxies.you can again use Scrapingdog for such services. The number of IPs in the world is fixed. By using these services you will get access to millions of IPs which can be used to scrape millions of pages. This is the best thing you can do to scrape successfully for a longer period of time.
3.User-Agent
The User-Agent request header is a character string that lets servers and network peers identify the application, operating system, vendor, and / or version of the requesting user agent.Some websites block certain requests if they contain User-Agent that don't belong to a major browser.If user-agents are not set many websites won't allow viewing their content.You can get your user-agent by typing What is my user agent on google.You
can also check your user-string here:
http://www.whatsmyuseragent.com/
Somewhat same technique is used by an anti-scraping mechanism that they use while banning IPs.If you are using the same user, agent, every request you will be banned in no time.What is the solution? Well, the solution is pretty simple you have to either create a list of User-Agents or maybe use libraries like fake-useragents . techniques but for efficiency purposes, I will urge you to use the library.A
user-agent string listing to get you started can be found here:
http://www.useragentstring.com/pages/useragentstring.php
https://developers.whatismybrowser.com/useragents/explore/
4. Make Scraping slower, keep Random Intervals in between
As you know the speed of crawling websites by humans and bots is very different. Bots can scrape websites at a very fast pace. Making fast unnecessary or random requests to a website is not good for anyone. Due to this overloading of requests a website may go down. To avoid this mistake, make your bot sleep programmatically in between scraping processes. This will make your bot look more human to the anti-scraping mechanism. This will also not harm the website. Scrape the smallest number of pages at a time By making concurrent requests. Put a timeout of around 10 to 20 seconds and then continue scraping. As I said earlier respect the robots.txt file.
Use auto throttling mechanisms which will automatically throttle the crawling speed based on the load on both the spider and the website that you are crawling. Adjust the spider to an optimum crawling speed after a few trials run. Do this periodically because the environment does change over time.
5. Change In Scraping Pattern Ando Detect Website Change
Generally, Humans Do Not Perform Repetitive Tasks As They Browse Through A Site With Random Actions. But Web Scraping Bots Will Crawl In The Same Pattern Because They Are Programmed To Do So. As I said earlier some websites have great anti-scraping mechanisms. The will catch your bot and will ban it permanently.
Now, how can you protect your bot from being caught? This can be achieved by Incorporating some random clicks on the page, mouse movements, and random actions that will make a spider look like a human. Now, another problem is many websites change their layouts for many reasons and due to this your scraper will fail to bring data you are expecting. For this, you should have a perfect monitoring system that detects changes in their layouts and then alert you with the scenario. Then this information can be used in your scraper to work accordingly.
One of my friends is working in a large online travel agency and they crawl the web to get prices of their competitors. While doing so they have a monitoring system that mails them every 15 minutes about the status of their layouts. This keeps everything on track and their scraper never breaks.
6. Headers
When you make a request to a website from your browser it sends a list of headers. Using headers, website analyses about your identity. To make your scraper look more human you can use these headers. Just copy them and paste them in your header object Inside your code. That will make your request look like it's coming from a real browser. On top of that using IP and User-Agent Rotation will make your scraper unbreakable. You can scrape any website whether it is dynamic or static.I am pretty sure using these techniques you will be able to beat 99.99% anti-scraping mechanisms. Now, there is a header “Referer”. It is an HTTP request header that lets the site know what site you are arriving from. General, it's a good idea to set this so that it looks like you're arriving from Google, you can do this with the header:
“Referer”: “https://www.google.com/”
You can replace it to https://www.google.co.uk or google.in if you are trying to scrape websites based in the UK or India. This will make your request look more authentic and organic. You can also look up the most common referrers to any site using a tool like https://www.similarweb.com, often this will be a social media site like Youtube or Facebook.
7. Headless Browser
Websites display their content on the basis of which browser you are using. Specific displays differently on different browsers. Let's take the example of Google search. If the browser (identified by the user agent) has advanced capabilities, the website may present “richer” content — something more dynamic and styled which may have a heavy reliance on Javascript and CSS.
The problem with this is that when doing any kind of web scraping, the content is rendered by the JS code and not the raw HTML response the server delivers. In order to scrape these websites, you may need to deploy your own headless browser (or Have Scrapingdog Do It For You!).
Automation Browsers Like Selenium Or Puppeteer Provides APIs To Control Browsers And Scrape Dynamic Websites. I Must Say A Lot Of Effort Goes In For Making These Browsers Go Undetectable. But His Is The Most Effective Way To Scrape You can even use certain browserless services to let you open an instance of a browser on their servers rather than increasing the load on your server.You can even open more than 100 instances at once on their services.So, all & all its a boon for the Scraping industry.
8. Captcha Solving Services
Many websites use ReCaptcha from Google which lets you pass a test. If the test goes successful within a certain time frame then it considers that you are not a bot but a real human being.f you are scraping a website on a large scale, the Website will eventually block you. You will start seeing captcha pages instead of web pages. There are services to get past these restrictions such as Scrapingdog. Note that some of these CAPTCHA solving services are fairly slow and expensive, so you may need to consider whether it is still economically viable to scrape sites that require continuous CAPTCHA solving over time.
9. Honeypot Traps
There are invisible links to detect hacking or web scraping.Actually it is an application that imitates the behavior of a real system.Certain websites have installed honeypots on their system which are invisible by a normal user but can be seen by bots or web scrapers. You need to find out whether a link has the “display: none” or “visibility: hidden” CSS properties set, and if they do avoid following that link, otherwise a site will be able to correctly identify you as a programmatic scraper, fingerprint The properties of your requests, and block you quite easily. Honeypots are one of the easiest ways for smart webmasters to detect crawlers, so make sure that you are performing this check on each page that you scrape.
10. Google Cache
Now, sometime google keeps a cached copy of some websites. So, rather than making a request to that website, you can also make a request to it cached copy.
“Http://webcache.googleusercontent.com/search?q = cache:” to the beginning of the URL. For example, to scrape documentation of Scrapingdog you could scrape “http://webcache.googleusercontent.com/search?q = cache: https: //www.scrapingdog.com/documentation ". But One Thing You Should Keep In Mind Is That This Technique Should Be Used For Websites That Do Not Have Sensitive Information Which Also Keeps Changing. For Example, Linkedin Tells Google To Not Cache Their Data. Google Also Creates A Cached Copy Of A website in a certain interval of time. It also depends on the popularity of the website.
Hopefully, you have learned new scraping tips by reading this article. I must remind you to keep respecting the robots.txt file. Also, try not to make large requests to smaller websites because they might not have the budget that large enterprises have.
Feel Free to comment and ask me anything. You can follow me on Twitter and Medium. Thanks for reading and please hit the like button! 👍
Additional Resources
And there's the list! At this point, you should feel comfortable writing your first web scraper to gather data from any website.Here are a few additional resources that you may find helpful during your web scraping journey:
List of web scraping proxy services
List of handy web scraping tools
BeautifulSoup Documentation
Scrapingdog Documentation
Guide to web scraping
この記事が気に入ったらサポートをしてみませんか?