Making A Web Scraper

Once you’ve put together enough web scrapers, you start to feel like you can do it in your sleep. I’ve probably built hundreds of scrapers over the years for my own projects, as well as for clients and students in my web scraping course.

Comparatively, it is very easier to scrape and extract intended data from any website manually by the creation of a simple web scraper with the help of an automated web data extraction tool. For such a purpose, you can easily make it through without feeling the need to develop a high-end web scraper or need not to write a code. The process of web scraping can be broken down into two main steps: Fetching the HTML source code of the website through an HTTP request or by using a headless browser. Parsing the raw data to extract just the information you're interested in. We'll examine both steps during the course of this tutorial. Greenpeace/check-my-pages Scraping script to test the Spanish Greenpeace web archive. Altsab/gowap Wappalyzer implementation in Go. Jesuiscamille/goquotes A quotes scrapper, making your day a little better! Jivesearch/jivesearch A search engine that doesn't track you. Leagify/colly-draft-prospects A scraper for future NFL Draft prospects. Using jsoup for web scraping. Jsoup is a popular Java-based HTML parser for manipulating and scraping data from web pages. The library is designed to work with real-world HTML, while implementing the best of HTML5 DOM (Document Object Model) methods and CSS selectors.

Occasionally though, I find myself referencing documentation or re-reading old code looking for snippets I can reuse. One of the students in my course suggested I put together a “cheat sheet” of commonly used code snippets and patterns for easy reference.

I decided to publish it publicly as well – as an organized set of easy-to-reference notes – in case they’re helpful to others.

While it’s written primarily for people who are new to programming, I also hope that it’ll be helpful to those who already have a background in software or python, but who are looking to learn some web scraping fundamentals and concepts.

Table of Contents:

  1. Extracting Content from HTML
  2. Storing Your Data
  3. More Advanced Topics

Web Scraper Extension

Useful Libraries

Free Online Web Scraper

For the most part, a scraping program deals with making HTTP requests and parsing HTML responses.

I always make sure I have requests and BeautifulSoup installed before I begin a new scraping project. From the command line:

Then, at the top of your .py file, make sure you’ve imported these libraries correctly.

Making Simple Requests

Make a simple GET request (just fetching a page)

Make a POST requests (usually used when sending information to the server like submitting a form)

Pass query arguments aka URL parameters (usually used when making a search query or paging through results)

Inspecting the Response

See what response code the server sent back (useful for detecting 4XX or 5XX errors)

Access the full response as text (get the HTML of the page in a big string)

Look for a specific substring of text within the response

Check the response’s Content Type (see if you got back HTML, JSON, XML, etc)

Extracting Content from HTML

Now that you’ve made your HTTP request and gotten some HTML content, it’s time to parse it so that you can extract the values you’re looking for.

Using Regular Expressions

Using Regular Expressions to look for HTML patterns is famously NOT recommended at all.

However, regular expressions are still useful for finding specific string patterns like prices, email addresses or phone numbers.

Run a regular expression on the response text to look for specific string patterns:

Using BeautifulSoup

BeautifulSoup is widely used due to its simple API and its powerful extraction capabilities. It has many different parser options that allow it to understand even the most poorly written HTML pages – and the default one works great.

Compared to libraries that offer similar functionality, it’s a pleasure to use. To get started, you’ll have to turn the HTML text that you got in the response into a nested, DOM-like structure that you can traverse and search

Look for all anchor tags on the page (useful if you’re building a crawler and need to find the next pages to visit)

Look for all tags with a specific class attribute (eg <li>...</li>)

Look for the tag with a specific ID attribute (eg: <div>...</div>)

Look for nested patterns of tags (useful for finding generic elements, but only within a specific section of the page)

Look for all tags matching CSS selectors (similar query to the last one, but might be easier to write for someone who knows CSS)

Get a list of strings representing the inner contents of a tag (this includes both the text nodes as well as the text representation of any other nested HTML tags within)

Return only the text contents within this tag, but ignore the text representation of other HTML tags (useful for stripping our pesky <span>, <strong>, <i>, or other inline tags that might show up sometimes)

Convert the text that are extracting from unicode to ascii if you’re having issues printing it to the console or writing it to files

Get the attribute of a tag (useful for grabbing the src attribute of an <img> tag or the href attribute of an <a> tag)

Putting several of these concepts together, here’s a common idiom: iterating over a bunch of container tags and pull out content from each of them

Using XPath Selectors

BeautifulSoup doesn’t currently support XPath selectors, and I’ve found them to be really terse and more of a pain than they’re worth. I haven’t found a pattern I couldn’t parse using the above methods.

If you’re really dedicated to using them for some reason, you can use the lxml library instead of BeautifulSoup, as described here.

Storing Your Data

Now that you’ve extracted your data from the page, it’s time to save it somewhere.

Note: The implication in these examples is that the scraper went out and collected all of the items, and then waited until the very end to iterate over all of them and write them to a spreadsheet or database.

I did this to simplify the code examples. In practice, you’d want to store the values you extract from each page as you go, so that you don’t lose all of your progress if you hit an exception towards the end of your scrape and have to go back and re-scrape every page.

Writing to a CSV

Probably the most basic thing you can do is write your extracted items to a CSV file. By default, each row that is passed to the csv.writer object to be written has to be a python list.

In order for the spreadsheet to make sense and have consistent columns, you need to make sure all of the items that you’ve extracted have their properties in the same order. This isn’t usually a problem if the lists are created consistently.

If you’re extracting lots of properties about each item, sometimes it’s more useful to store the item as a python dict instead of having to remember the order of columns within a row. The csv module has a handy DictWriter that keeps track of which column is for writing which dict key.

Writing to a SQLite Database

You can also use a simple SQL insert if you’d prefer to store your data in a database for later querying and retrieval.

More Advanced Topics

These aren’t really things you’ll need if you’re building a simple, small scale scraper for 90% of websites. But they’re useful tricks to keep up your sleeve.

Javascript Heavy Websites

Contrary to popular belief, you do not need any special tools to scrape websites that load their content via Javascript. In order for the information to get from their server and show up on a page in your browser, that information had to have been returned in an HTTP response somewhere.

It usually means that you won’t be making an HTTP request to the page’s URL that you see at the top of your browser window, but instead you’ll need to find the URL of the AJAX request that’s going on in the background to fetch the data from the server and load it into the page.

There’s not really an easy code snippet I can show here, but if you open the Chrome or Firefox Developer Tools, you can load the page, go to the “Network” tab and then look through the all of the requests that are being sent in the background to find the one that’s returning the data you’re looking for. Start by filtering the requests to only XHR or JS to make this easier.

Once you find the AJAX request that returns the data you’re hoping to scrape, then you can make your scraper send requests to this URL, instead of to the parent page’s URL. If you’re lucky, the response will be encoded with JSON which is even easier to parse than HTML.

Content Inside Iframes

This is another topic that causes a lot of hand wringing for no reason. Sometimes the page you’re trying to scrape doesn’t actually contain the data in its HTML, but instead it loads the data inside an iframe.

Again, it’s just a matter of making the request to the right URL to get the data back that you want. Make a request to the outer page, find the iframe, and then make another HTTP request to the iframe’s src attribute.

Sessions and Cookies

While HTTP is stateless, sometimes you want to use cookies to identify yourself consistently across requests to the site you’re scraping.

The most common example of this is needing to login to a site in order to access protected pages. Without the correct cookies sent, a request to the URL will likely be redirected to a login form or presented with an error response.

However, once you successfully login, a session cookie is set that identifies who you are to the website. As long as future requests send this cookie along, the site knows who you are and what you have access to.

Delays and Backing Off

If you want to be polite and not overwhelm the target site you’re scraping, you can introduce an intentional delay or lag in your scraper to slow it down

Some also recommend adding a backoff that’s proportional to how long the site took to respond to your request. That way if the site gets overwhelmed and starts to slow down, your code will automatically back off.

Making

Spoofing the User Agent

By default, the requests library sets the User-Agent header on each request to something like “python-requests/2.12.4”. You might want to change it to identify your web scraper, perhaps providing a contact email address so that an admin from the target website can reach out if they see you in their logs.

More commonly, this is used to make it appear that the request is coming from a normal web browser, and not a web scraping program.

Using Proxy Servers

Even if you spoof your User Agent, the site you are scraping can still see your IP address, since they have to know where to send the response.

If you’d like to obfuscate where the request is coming from, you can use a proxy server in between you and the target site. The scraped site will see the request coming from that server instead of your actual scraping machine.

If you’d like to make your requests appear to be spread out across many IP addresses, then you’ll need access to many different proxy servers. You can keep track of them in a list and then have your scraping program simply go down the list, picking off the next one for each new request, so that the proxy servers get even rotation.

Setting Timeouts

If you’re experiencing slow connections and would prefer that your scraper moved on to something else, you can specify a timeout on your requests.

Handling Network Errors

Just as you should never trust user input in web applications, you shouldn’t trust the network to behave well on large web scraping projects. Eventually you’ll hit closed connections, SSL errors or other intermittent failures.

Learn More

If you’d like to learn more about web scraping, I currently have an ebook and online course that I offer, as well as a free sandbox website that’s designed to be easy for beginners to scrape.

You can also subscribe to my blog to get emailed when I release new articles.

Wednesday, January 20, 2021

There are many free web scraping tools. However, not all web scraping software is for non-programmers. The lists below are the best web scraping tools without coding skills at a low cost. The freeware listed below is easy to pick up and would satisfy most scraping needs with a reasonable amount of data requirement.

Table of content

Web Scraper Client

1. Octoparse

Octoparse is a robust web scraping tool which also provides web scraping service for business owners and Enterprise. As it can be installed on both Windows and Mac OS, users can scrape data with apple devices.Web data extraction includes but not limited to social media, e-commerce, marketing, real estate listing and many others. Unlike other web scrapers that only scrape content with simple HTML structure, Octoparse can handle both static and dynamic websites with AJAX, JavaScript, cookies and etc. You can create a scraping task to extract data from a complex website such as a site that requires login and pagination. Octoparse can even deal with information that is not showing on the websites by parsing the source code. As a result, you can achieve automatic inventories tracking, price monitoring and leads generating within fingertips.

Octoparse has the Task Template Mode and Advanced Mode for users with both basic and advanced scraping skills.

  • A user with basic scraping skills will take a smart move by using this brand-new feature that allows him/her to turn web pages into some structured data instantly. The Task Template Mode only takes about 6.5 seconds to pull down the data behind one page and allows you to download the data to Excel.
Free online web scraper
  • The Advanced mode has more flexibility comparing the other mode. This allows users to configure and edit the workflow with more options. Advance mode is used for scraping more complex websites with a massive amount of data. With its industry-leading data fields auto-detectionfeature, Octoparse also allows you to build a crawler with ease. If you are not satisfied with the auto-generated data fields, you can always customize the scraping task to let itscrape the data for you.The cloud services enable to bulk extract huge amounts of data within a short time frame since multiple cloud servers concurrently run one task. Besides that, thecloud servicewill allow you to store and retrieve the data at any time.

2. ParseHub

Making A Web Scraper

Parsehub is a great web scraper that supports collecting data from websites that use AJAX technologies, JavaScript, cookies and etc. Parsehub leverages machine learning technology which is able to read, analyze and transform web documents into relevant data.

Money

The desktop application of Parsehub supports systems such as Windows, Mac OS X, and Linux, or you can use the browser extension to achieve an instant scraping. It is not fully free, but you still can set up to five scraping tasks for free. The paid subscription plan allows you to set up at least 20 private projects. There are plenty of tutorials for at Parsehub and you can get more information from the homepage.

3. Import.io

Import.io is a SaaS web data integration software. It provides a visual environment for end-users to design and customize the workflows for harvesting data. It also allows you to capture photos and PDFs into a feasible format. Besides, it covers the entire web extraction lifecycle from data extraction to analysis within one platform. And you can easily integrate into other systems as well.

4. Outwit hub

Outwit hub is a Firefox extension, and it can be easily downloaded from the Firefox add-ons store. Once installed and activated, you can scrape the content from websites instantly. It has an outstanding 'Fast Scrape' features, which quickly scrapes data from a list of URLs that you feed in. Extracting data from sites using Outwit hub doesn’t demand programming skills. The scraping process is fairly easy to pick up. You can refer to our guide on using Outwit hub to get started with web scraping using the tool. It is a good alternative web scraping tool if you need to extract a light amount of information from the websites instantly.

Web Scraping Plugins/Extension

1. Data Scraper (Chrome)

Data Scraper can scrape data from tables and listing type data from a single web page. Its free plan should satisfy most simple scraping with a light amount of data. The paid plan has more features such as API and many anonymous IP proxies. You can fetch a large volume of data in real-time faster. You can scrape up to 500 pages per month, you need to upgrade to a paid plan.

2. Web scraper

Web scraper has a chrome extension and cloud extension. For chrome extension, you can create a sitemap (plan) on how a website should be navigated and what data should be scrapped. The cloud extension is can scrape a large volume of data and run multiple scraping tasks concurrently. You can export the data in CSV, or store the data into Couch DB.

3. Scraper (Chrome)

The scraper is another easy-to-use screen web scraper that can easily extract data from an online table, and upload the result to Google Docs.

Just select some text in a table or a list, right-click on the selected text and choose 'Scrape Similar' from the browser menu. Then you will get the data and extract other content by adding new columns using XPath or JQuery. This tool is intended for intermediate to advanced users who know how to write XPath.

Web-based Scraping Application

1. Dexi.io (formerly known as Cloud scrape)

Dexi.io is intended for advanced users who have proficient programming skills. It has three types of robots for you to create a scraping task - Extractor, Crawler, and Pipes. It provides various tools that allow you to extract the data more precisely. With its modern feature, you will able to address the details on any websites. For people with no programming skills, you may need to take a while to get used to it before creating a web scraping robot. Check out their homepage to learn more about the knowledge base.

The freeware provides anonymous web proxy servers for web scraping. Extracted data will be hosted on Dexi.io’s servers for two weeks before archived, or you can directly export the extracted data to JSON or CSV files. It offers paid services to meet your needs for getting real-time data.

2. Webhose.io

Webhose.io enables you to get real-time data from scraping online sources from all over the world into various, clean formats. You even can scrape information on the dark web. This web scraper allows you to scrape data in many different languages using multiple filters and export scraped data in XML, JSON, and RSS formats.

The freeware offers a free subscription plan for you to make 1000 HTTP requests per month and paid subscription plans to make more HTTP requests per month to suit your web scraping needs.

Author: Ashley

Ashley is a data enthusiast and passionate blogger with hands-on experience in web scraping. She focuses on capturing web data and analyzing in a way that empowers companies and businesses with actionable insights. Read her blog here to discover practical tips and applications on web data extraction

日本語記事:無料で使えるWebスクレイピングツール9選
Webスクレイピングについての記事は 公式サイトでも読むことができます。
Artículo en español: 9 Web Scraping Gratuitos que No Te Puedes Perder en 2021
También puede leer artículos de web scraping en el Website Oficial