# The BeautifulSoup Package

> Prerequisite: [the `requests` package](/intro-to-python/notes/python/packages/requests.md)

The `BeautifulSoup` package provides a simple way of parsing a website's HTML contents.

Reference: <https://www.crummy.com/software/BeautifulSoup/bs4/doc/>.

## Installation

First install the package, if necessary:

```bash
pip install beautifulsoup4 # note the 4 at the end - this is the latest version
```

## Usage

You can use this package from the command line or from within a script. The examples below depict usage from within a script.

When you make a request that returns some HTML string, you can parse it like this:

```python
import requests
from bs4 import BeautifulSoup # note that the import package command is `bs4`

response = requests.get("https://www.gutenberg.org/ebooks/author/65")
response_html = response.text

soup = BeautifulSoup(response_html)

titles = soup.find_all("span", "title")

print(type(titles)) #> <class 'bs4.element.ResultSet'> (like a list)
print(titles[5]) #> <span class="title">Romeo and Juliet</span>
print(titles[5].text) #> Romeo and Juliet

booklinks = soup.find_all("li", "booklink")

books = []
for list_item in booklinks:
    try:
        title = list_item.find("span", "title").text #> "Shakespeare's Sonnets"
        author = list_item.find("span", "subtitle").text #> "William Shakespeare"
        downloads = list_item.find("span", "extra").text #> '830 downloads'
        downloads_count = int(downloads.replace(" downloads", "")) #> 830
        book = {"title": title, "author": author, "downloads": downloads_count}
        print(book)
        books.append(book)
    except Exception as err:
        print("OOPS", type(err), err, "SKIPPING...")

print(books[2]["title"]) #> Romeo and Juliet
```

It's easier to parse HTML once you know the document structure. Try using your browser's developer tools to examine the document structure of any web page. For example, in Google Chrome you can right-click on a webpage and select "Inspect".


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://prof-rossetti.gitbook.io/intro-to-python/notes/python/packages/beautifulsoup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
