

Learning to scrape websites using the Beautifulsoup and Requests libraries
With this tutorial we're starting a course that we've been asked about a lot - a course on data parsing using Python. We have already talked about parsing without programming , using browser extensions, but their capabilities are limited and are not suitable for all sites. But Python will help you parse almost anything.
To parse correctly, you need to understand how sites are structured. Almost all of them are designed using HTML. Let's understand its structure using the KinoPoisk website as an example and try to parse the list of the 250 best films according to the site's users.
Many sites from which journalists sometimes need to collect data are structured in a similar way to KinoPoisk, so it is a good example.

For this course we use the Google Chrome browser, so to make it easier for you to understand our actions and not get confused by the names of functions, we recommend using the same browser. But other browsers, Firefox or Opera, for example, also have all these functions.
If you right-click anywhere on the site and click on “ View code ”, a panel with HTML code will appear on the right (also called the developer panel).

This language is based on tags. The main one is html , the head usually contains meta information (heading, for example), and we are now interested in the body tag, where the main information of the page lies.

To view the code of a specific element, you need to click on it and click “ View code ” - then the required tag will be highlighted in the developer panel.

And vice versa, if you move along the code in the panel on the right, then on the left, on the page itself, the element laid out with this tag will be highlighted.
On listing pages, the same tags (title, rating, etc.) are repeated from card to card. Therefore, these specific tags need to be detected and written out. But first, let’s pull out the entire code of the page, and this is where the Requests library comes in handy - we’ve already talked about it, we advise you to first read that lesson and install it.
Open Jupyter , import the library using import requests . To access a site, we create a url variable and assign it the value of the desired site (for us this is a link to the top “KinoPoisk”).

Let's send a request to the server using the get command, to the input of which we pass the url variable. Let's see what happens using the text command.

As you can see, the code turned out to be unreadable. Another library, Beautifulsoup , will help you cope with this. We import it using the command from bs4 import BeautifulSoup . This may require you to first install the library via pip install .

We must pass the response received using Requests to the library. Let's create a soup variable, pass r.text and specify the required format (in our case lxml ).

The code is ordered, the tags go one by one - now we can take out what we need from the code. To do this, go back to the browser, to the data page. As you can see in the screenshot, there are several div tags in a row with the class desktop-rating-selection-file-item - this is a card for each of the films in the list.

First, we will extract the data only from the first card, and then we will rewrite the code so that it works for all films from the page. Let's copy the name of the class - to do this, double-click on it with the mouse and press Ctrl+C ( Cmd+C for macOS).
Beautifulsoup has a find command - we indicate to it the desired tag ( div ) and the class separated by commas ( desktop-rating-selection-file-item ). After class you must put an underscore.

Not the entire code was displayed, but only the required element, in which the name of the film is visible. Let's return to the site to delve deeper into the card and see the names of the parts we need. Click on the title of the movie “The Green Mile” and select “ View Code ” again.
For example, we see that the link to the movie is in the a tag and has its own class selection-film-item-meta__link . The a tag, in turn, contains p tags with Russian and original movie titles. We will take these three elements.

Let's add to our first command: put a period, write find again, indicate the a tag and its class.

To make a link to a movie work, you first need to add a domain to it. The link itself is inside the tag, so we won’t be able to use find . Let's use the get command and specify the required attribute (in our case, href ).

Let’s add the “KinoPoisk” domain to the beginning of the command and run it again - this way we’ll get a ready-made link. Let's put this code in the link variable.

By analogy, we will get the Russian-language and original names. Let's take the same code, add a new find , and indicate the required tag and class. To clear the result of unnecessary code elements, add a text command at the end. Let's call these variables russian_name and original_name, respectively.

We can also get the country of production and genre from the card - everything will work exactly the same, only the class will not be p , like the names, but span . Let's put the country in the country variable.
However, in the KinoPoisk code, country and genre have the same class selection-film-item-meta__meta-additional-item - and the find command finds only the first match to your request. Let's use the findAll command and leave everything else as before to get a list.

To pull out only the genre, add numbering in square brackets (remember that in Python we start from 0 , so we need the number 1 ) and the text command. Let's call the variable film_type .

We got basic information about the film, but we can also get something else - for example, a rating. Let’s check the name of the class of this element on the KinoPoisk page using the already known “View code” method. As you can see, we are lucky - the class has a unique name, so we don’t have to dig deep.

Let’s copy that part of the original find command, where we go to the first div of the movie card and immediately specify a new search using the span tag and the rating__value rating__value_positive class (and don’t forget about text ). Let's call the variable rate .

We've already done almost all the work, but so far our code only works for the first movie card in the list. Let's fix this. Let's create a variable films , set a new search for the very first div , but with the findAll command. And at the same time, let's look at the length of the list using the len command. There will be 50 of them, because the top 250 list is divided into 5 pages. Next, we will teach the code to navigate other pages.

Let's write a loop for each film in the films list. For now, let’s copy the link search command and see what needs to be corrected there. We don't need a query for the first div because we previously accessed it using findAll - let's replace it with film . Let's repeat this with each element.

Let's create a data variable to which we will add all the variables that we request.

Let's run the code and see what is displayed in data .

Everything is exactly as we needed. All that remains is to figure out how to collect data from the following pages. If we go to the second page of the list, we will see that the link in the browser address bar has changed - page=2 appears there.

That is, we need to pass this parameter to the loop. Let's create a url variable before the loop and use the f-string method to place inside the curly braces the parameter we need - the page number. Let's call the parameter p and place it in a loop in the range from 1 to 6 .
In this case, the data variable must be placed at the beginning of the code so that it is not overwritten with each new cycle, but is supplemented. After that, let's copy the code to run Requests and Beautifulsoup .
Sorry, there is an error on the screenshot: the last value in range must be 6, otherwise the script will only go through four pagesThe code is ready to go. But we also recommend adding time intervals between requests so as not to overload the server we are accessing. Let's go back to the area where we previously imported Beautifulsoup and import the sleep function from the time library.

We will add to the main code so that 3 seconds pass between requests. To check the functionality of the script in real time, add the print command.
The error from the screenshot before last has been corrected: the last value in range is 6, so the script went through all five pagesEverything should work. If we now check the length of our list again with the command len(data) , it will be 250 - just like in the KinoPoisk top. Now let's save our data into a table. Let's go back to the import area and add Pandas there and use it to write to csv .

Let's enter names for the columns - let them duplicate the names of the variables that we assigned earlier (don't forget to put them in 'quotes'). And after that we export our data.


The last thing we will look at in this lesson is how to teach the code not to break and continue working if the movie does not have one of the parameters specified. Let's write, for example, an exception for the film rating ( rate ) - if it doesn't exist, there will be a dash.

KinoPoisk responded to our script without any problems, but there are sites whose requests do not want to give us the necessary information. We'll tell you how to deal with this in the following lessons.
If something doesn’t work out for you, write to our Telegram chat , we’ll try to help.