---
title: "Web Scraping in Python Using BeautifulSoup HTML Parser"
description: "While there are many ways to do it, using Python with BeautifulSoup is one of the most popular web scraping methods. Read on to learn why!"
url: "https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/"
---

- [EN - English](https://iproyal.com/)
   
  [中文 - Chinese](https://china-iproyal.com/)

[Book a Demo](https://iproyal.com/request-a-demo/) [Create Account](https://dashboard.iproyal.com/register/) [Create Account](https://dashboard.iproyal.com/register/) [Login](https://dashboard.iproyal.com/login/) [Login](https://dashboard.iproyal.com/login/)

[Book a Demo](https://iproyal.com/request-a-demo/)

[Back to blog](https://iproyal.com/blog/)

# Web Scraping in Python Using BeautifulSoup HTML Parser

[Eugenijus Denisov](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Last updated - August 10, 2023 ‐ 11 min read](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Python](https://iproyal.com/blog/category/python/)

Web scraping typically involves two key tasks: getting data from the web and extracting valuable information from it. For the first one, Python users typically use a library like [Requests ](https://pypi.org/project/requests/), while for the second, [BeautifulSoup ](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)is frequently used.

BeautifulSoup is one of the most popular Python libraries for HTML parsing because it’s simple to use and works well with both HTML and XML documents. Its ease in navigating a parse tree and extracting nested elements makes it a go-to Python library for many developers starting a web scraping project.

We’ll explore BeautifulSoup’s extensive range of features, covering both basic and advanced functionality. In addition, you’ll learn how to use the various features of the library to scrape [Books to Scrape ](https://books.toscrape.com/), a sandbox website for learning [web scraping ](https://www.webscrapingapi.com/)that displays a list of books and their prices.

## Setup

BeautifulSoup is a Python library, so you’ll need Python installed on your machine. If you don’t have it already, you can get it from the official [downloads ](https://www.python.org/downloads/)page.

In addition to that, you’ll need to install the Requests and BeautifulSoup libraries. You can do that with the following commands:

```javascript
pip install requests beautifulsoup4
```

Create a new folder, and create a new Python file called `soup.py` inside it. Then, open it in your favorite code editor and import the libraries at the top.

```python
import requests
from bs4 import BeautifulSoup
```

## Downloading HTML

BeautifulSoup can parse the HTML content of a site and extract valuable information from it. But to do that, you first need to get the HTML file of the web page itself. For that, developers usually use [Requests ](https://requests.readthedocs.io/en/latest/)or a browser automation library like Selenium or Playwright.

Requests is an HTTP client library, which means that it can communicate with HTTP servers and get information from them, just like a regular browser would.

For example, here's how you can get the HTML code of Books to Scrape:

```python
r = requests.get("https://books.toscrape.com/")
soup = BeautifulSoup(r.content, 'html.parser')
print(r.content)
```

This should print out a large batch of HTML in your console. If you want to get the valuable information inside it, you'll need to parse it to get rid of all the unnecessary parts. This is where BeautifulSoup comes in.

## Extracting Data From HTML With BeautifulSoup

### .text vs .get()

If you have a BeautifulSoup object for a tag, using *.text* returns all the textual content inside the tag (and its children), with tags stripped out. For example:

```python
tag = soup.find('h3').find('a')
print(tag.text)
```

*.get("attribute_name")* is used to fetch a particular attribute value (for example, *href, src, title*) on an HTML tag:

```python
print(tag.get('href'))
print(tag.get('title'))
```

Use *.get()* when you want the HTML data in an attribute, and *.text* when you want the visible text between tags.

### Attribute Extraction (href, src, etc.)

You will often want to extract links, image sources, or more. For example:

```python
for anchor in soup.find_all("a"):
    link = anchor.get("href")
    print("https://books.toscrape.com/" + link)
```

Or:

```python
img = soup.find("img")
src = img.get("src")
print("https://books.toscrape.com/" + src)
```

It’s how you extract data from XML and HTML documents where the information is stored in attributes.

### Extracting Structured Data (Lists, Nested Elements)

Often, the data you want is repeated or nested inside parent containers. You can use *find_all()* or *.select()* to get lists of container tags and then loop, drilling deeper to get individual fields.

For example:

```python
containers = soup.find_all(class_="product_pod")
books = []
for cont in containers:
    title = cont.find("h3").a.get("title")
    price = cont.find(class_="price_color").text
    books.append({"title": title, "price": price})
for book in books[:3]: # Limits length to 3 elements
    print(book)
```

If the HTML structure is more nested (for instance, a table), you might do:

```python
rows = table.find_all("tr")
for row in rows:
    cols = row.find_all("td")
    # then extract each column
```

## Parsing HTML

To start using BeautifulSoup, you need to take the HTML file code you received from *requests.get()* and parse it.

```python
soup = BeautifulSoup(r.content, "html.parser")
```

This will parse the website HTML document into an easily searchable object.

## Finding Elements in HTML Documents

Now, you can use the library to locate the HTML web elements you need in the library. One of the ways to do that is via the find method. It locates the first element that matches a given query.

Try adding the following to your `soup.py` file:

```python
h3 = soup.find("h3")
print(h3)
```

Running it will print out the first h3 element of the page.

```html
<h3><a href="catalogue/a-light-in-the-attic_1000/index.html" title="A Light in the Attic">A Light in the ...</a></h3>
```

You can also find elements by class or by ID. For example:

```python
product = soup.find(class_="product_pod")
print(product)
```

The code above will find the first element with the class of *product_pod.*

```html
<article class="product_pod">
<div class="image_container">
<a href="catalogue/a-light-in-the-attic_1000/index.html"><img alt="A Light in the Attic" class="thumbnail"
src="media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg"/></a>
...
```

Once you have an element, you can extract information from this element using attributes like text.

```python
h3 = soup.find("h3")
title = h3.text
print(title)
```

This will return the text of the first h3 heading, which is the displayed title of the first book.

```javascript
A Light in the ...
```

To get the displayed titles of all the books on the page, you can use the *find_all* method. Instead of returning just one result, it returns a list of all matching elements.

```python
h3s = soup.find_all("h3")
```

You can further iterate over that list using a for loop or list comprehension.

```python
titles = [h3.text for h3 in h3s]
print(titles)
```

Which returns the following result:

```typescript
['A Light in the ...', 'Tipping the Velvet', 'Soumission', 'Sharp Objects', 'Sapiens: A Brief History ...', 'The Requiem Red', 'The Dirty Little Secrets ...', 'The Coming Woman: A ...', 'The Boys in the ...', 'The Black Maria', 'Starving Hearts (Triangular Trade ...', "Shakespeare's Sonnets", 'Set Me Free', "Scott Pilgrim's Precious Little ...", 'Rip it Up and ...', 'Our Band Could Be ...', 'Olio', 'Mesaerion: The Best Science ...', 'Libertarianism for Beginners', "It's Only the Himalayas"]
```

There's just one issue: titles sometimes get shortened when they are displayed on the page.

But if you look at the HTML file, you'll see that the full title is stored in the title attribute of the anchor tag that's inside the h3.

```html
<h3><a href="catalogue/a-light-in-the-attic_1000/index.html" title="A Light in the Attic">A Light in the ...</a></h3>
```

To extract it, you need to:

- Move from the h3 inside the anchor tag.
- Access the title attribute of the anchor element using the get method.

Here's the code that does that:

```python
titles = [h3.a.get("title") for h3 in h3s]
```

## CSS Selectors

In addition to methods like find and *find_all,* BeautifulSoup offers support for CSS selectors.

CSS selectors are a versatile and widely supported method for locating specific HTML elements. Compared to other element selection methods, CSS selectors offer broader functionality, making them an invaluable tool in a web scraper's arsenal.

You can use CSS selectors via the select function, which takes a string (CSS selector) and returns a list of elements that match this selector.

Querying a single tag works the same as when using *find_all.*

```python
h3s = soup.select("h3")
```

But CSS selectors offer much more flexible capabilities through the use of combinators and pseudo-classes.

### Combinators

There are four [combinators ](https://www.w3schools.com/css/css_combinators.asp)in CSS selectors, but the most useful in web scraping are descendant combinator (empty space) and child combinator (>). They can be used to match tags that are nested within other tags.

The difference between them is that the descendant combinator matches as many levels deep as it needs, while the child combinator only matches one level deep.

For example, you can use a child combinator to select all the anchor tags that are inside h3 tags.

```python
anchors = soup.select("h3 > a")
```

It will match all anchors that are inside h3 tags.

## Pseudo-classes

In CSS, [pseudo-classes ](https://www.w3schools.com/css/css_pseudo_classes.asp)are commonly used to denote a particular state of the element, such as when it is hovered over, clicked, etc.

But CSS selectors can select by a very useful pseudo-class called [:nth-child ](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child/), which enables you to select an arbitrary child of an element by number or by some pattern such as repeating number, odd, or even.

For example, let's say you want to get the name of the fifth category on the Books to Scrape website's list of categories.

First, you need to locate the list using child selectors, and then you can extract the fifth element using the *nth-child* pseudo-class.

```python
fifth_category = soup.select("ul.nav > li > ul> li:nth-child(5)")
print(fifth_category[0].text.strip())
```

The code above should print out the name of the category — classics.

This can be very useful for websites where elements don't use proper class names. In such a case, you can make web scraping scripts that depend on element order.

## Scraping a Website With BeautifulSoup

Now that you've learned how to use the various features of BeautifulSoup, you can try to scrape the titles and prices of books from the Books to Scrape website.

Create a new file called `books.py` and import the libraries you’ll use:

```python
import requests
from bs4 import BeautifulSoup
```

After that, request the website and parse the results.

```python
r = requests.get("https://books.toscrape.com/")

soup = BeautifulSoup(r.content, "html.parser")
```

Then find all the div elements surrounding individual books (they have the class of *product_pod).*

```python
products = soup.find_all(class_="product_pod")
```

Finally, you need to iterate over these elements to extract the necessary information.

```python
books = []

for product in products: 
    title = product.find("h3").a.get("title")
    price = product.find(class_="price_color").text 
    books.append({"title": title, "price": price})

print(books)
```

The code above creates a new list called books. For each book, it:

- Extracts the title attribute of the anchor that's inside the h3 tag.
- Extracts the price by finding its tag, conveniently marked with *price_color,* and extracting all the text that's inside that tag.

It then creates a dictionary for the item and adds it to the book list.

Finally, it prints out all the books.

Running it with python `books.py` should return the following:

```typescript
[{'title': 'A Light in the Attic', 'price': '£51.77'}, {'title': 'Tipping the Velvet', 'price': '£53.74'}, {'title': 'Soumission', 'price': '£50.10'}, {'title': 'Sharp Objects', 'price': '£47.82'}, {'title': 'Sapiens: A Brief History of Humankind', 'price': '£54.23'}, {'title': 'The Requiem Red', 'price': '£22.65'}, {'title': 'The Dirty Little Secrets of Getting Your Dream Job', 'price': '£33.34'} … ]
```

### Common Errors & Troubleshooting

- If your *find()* returns *None,* trying *.text* or *.get()* will raise an error. Always check for *None.*
- If *find_all()* returns *\[],* that means no matching HTML tags were found. Maybe your selector is wrong or the HTML file structure has changed.
- Sometimes characters can appear garbled. You may need *.encoding* or decode the bytes appropriately.
- When *.content* gives bytes, sometimes *.text* on the response helps with correct decoding.

### Examples of Different HTML File Structures

#### Table-Based Layout

```html
<table>
  <tr><td>Name</td><td>Price</td></tr>
  <tr><td>Book A</td><td>£20</td></tr>
</table>
```

You’d parse it with *.find("table"),* then iterate rows and columns.

#### Nested Divs

```html
<div class="item">
  <div class="header"><h2>Title</h2></div>
  <div class="meta"><span class="price">£10</span></div>
</div>
```

You’d first get all *.item* divs, then within each get *div.header h2* or *div.meta span.price.*

### Rate-Limiting and Best Practices

Follow these best practices to have the best experience while scraping HTML documents:

- Don’t overload the server. Add delays between requests.
- Use headers so you look like a standard browser.
- Use proxies to lower the chances of getting flagged and blocked.
- Respect *robots.txt* and the website’s terms of service.
- Cache responses when possible to avoid re-requesting the same pages.

## Do You Need a Proxy With BeautifulSoup?

BeautifulSoup is a parsing library, which means that it doesn't itself interact with the internet in any capacity—all it does is parse HTML files using the selectors that you provide. But web scraping, of course, does involve the internet. And whenever you're scraping the internet, you need to be careful about not raising the suspicion of website administrators.

For this reason, people who perform web scraping tasks typically use proxies. Proxies act as an intermediary between you and the site you're trying to scrape, which helps to obscure your real IP address. If you manage to alert the owners of the website, they just ban the proxy, and you can continue scraping the site.

A premium proxy solution like IPRoyal [residential proxies ](https://iproyal.com/residential-proxies/)will give you access to a rotating pool of proxies that will provide you with a new IP on every request. Here's how you can use them with the scraping setup that's used in this article.

First, you need to find the link to your proxy. If you're using IPRoyal, it's conveniently located in the dashboard.

Then you need to add this link to your HTTP request that you make using Requests.

To do that, first create a dictionary that contains the link to your proxies, replacing the values with the link to your real proxy.

```python
proxies = {
   'http': 'link-to-proxy',
   'https': 'link-to-proxy',
}
```

Then, add the proxy dictionary to the Requests calls that you're making.

```python
r = requests.get("https://books.toscrape.com/", proxies=proxies)
```

Now your IP address will be properly protected and won't be available to website owners.

## Conclusion

BeautifulSoup is a very powerful web scraping tool, and it's essential to know how to use it. With the help of element locators and CSS selectors, it can easily tackle even websites that try to prevent web scraping by obscuring HTML.

But, of course, the Requests + BeautifulSoup approach is not suited for every web scraping task. BeautifulSoup can only parse HTML documents, which means that it cannot interact well with dynamic websites that use JavaScript. To parse these sites, you'll need a more heavyweight tool like [Selenium ](https://iproyal.com/blog/web-scraping-with-selenium-and-python/).

## FAQ

How to click on items with BeautifulSoup?

BeautifulSoup is a parsing library, and so cannot interact with web elements the same way a browser would be able to. For basic navigation, you can use BeautifulSoup to extract the link of a website you want to visit, and then use the Requests library to navigate to that link. This pattern can be useful in handling paginated websites, for example.

My BeautifulSoup scraper returns *\[]* or *None.* What should I do?

In this case, you need to check whether your selectors/methods are correct for the HTML document that you are trying to parse. Commonly, BeautifulSoup returns *\[]* when no element matches the given query, while *None* is returned when you try to access a property of an element that is not there.

How to get the text of an HTML element in BeautifulSoup?

Once you have located an HTML element, you can extract its text using the .text property.

[Create Account](https://dashboard.iproyal.com/)

[Author](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Eugenijus Denisov](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Lead Backend Developer](https://iproyal.com/blog/authors/eugenijus-denisov/)

With over a decade of experience under his belt, Eugenijus has worked on a wide range of projects - from LMS (learning management system) to large-scale custom solutions for businesses and the medical sector. Proficient in PHP, Vue.js, Docker, MySQL, and TypeScript, Eugenijus is dedicated to writing high-quality code while fostering a collaborative team environment and optimizing work processes. Outside of work, you’ll find him running marathons and cycling challenging routes to recharge mentally and build self-confidence.

[Learn More About Eugenijus Denisov ](https://iproyal.com/blog/authors/eugenijus-denisov/)[Meet all Writers](https://iproyal.com/blog/authors/)

Share on

### In This Article

- [Setup](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Setup)
- [Downloading HTML](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Downloading-HTML)
- [Extracting Data From HTML With BeautifulSoup](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Extracting-Data-From-HTML-With-BeautifulSoup)
- [Parsing HTML](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Parsing-HTML)
- [Finding Elements in HTML Documents](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Finding-Elements-in-HTML-Documents)
- [CSS Selectors](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#CSS-Selectors)
- [Pseudo-classes](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Pseudo-classes)
- [Scraping a Website With BeautifulSoup](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Scraping-a-Website-With-BeautifulSoup)
- [Do You Need a Proxy With BeautifulSoup?](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Do-You-Need-a-Proxy-With-BeautifulSoup)
- [Conclusion](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#Conclusion)
- [FAQ](https://iproyal.com/blog/web-scraping-in-python-using-beautiful-soup/#FAQ)

Ready to get started?

[Register now](https://dashboard.iproyal.com/register/)

Data News in Your Inbox

No spam whatsoever, just pure data gathering news, trending topics and useful links. Unsubscribe anytime.

No spam. Unsubscribe anytime.

## Related articles

[View all](https://iproyal.com/blog/category/python/)

[Python](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

## [How to Parse JSON in Python: Read, Write & Work With JSON Files](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[Learn how to read, write, and parse JSON in Python using the built-in JSON module and custom classes for clean, efficient data handling.](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[January 31, 2023](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[9 min read](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[Python](https://iproyal.com/blog/python-syntax-errors/)

## [Python Syntax Errors: What They Are and How to Fix Them](https://iproyal.com/blog/python-syntax-errors/)

[Find out why you get syntax errors and how you can fix them quickly and effectively.](https://iproyal.com/blog/python-syntax-errors/)

[October 24, 2024](https://iproyal.com/blog/python-syntax-errors/)

[6 min read](https://iproyal.com/blog/python-syntax-errors/)

[Python](https://iproyal.com/blog/python-xml-parsing/)

## [Python XML Parsing: Full Guide](https://iproyal.com/blog/python-xml-parsing/)

[Find out how to use Python to parse XML files effectively and what are the most popular libraries for the job.](https://iproyal.com/blog/python-xml-parsing/)

[November 25, 2024](https://iproyal.com/blog/python-xml-parsing/)

[9 min read](https://iproyal.com/blog/python-xml-parsing/)
