Python Web Scraping - BeautifulSoup
Python web scraping refers to the process of automatically extracting information from the internet by writing Python programs.
The basic scraping flow usually consists of sending an HTTP request to get the web page content, parsing the page and extracting data, and then storing the data.
Python's rich ecosystem makes it a popular language for developing crawlers, especially thanks to its powerful library support.
Generally, the scraping flow can be divided into the following steps:
- Send an HTTP request: The crawler gets the HTML page from the target site through an HTTP request; commonly used libraries include
requests。 - Parse the HTML content: After getting the HTML page, the crawler needs to parse the content and extract data; commonly used libraries include
BeautifulSoup、lxml、Scrapy, etc. - Extract data: Extract the required data by locating HTML elements (such as tags, attributes, class names, etc.).
- Store data: Store the extracted data in a database, CSV file, JSON file or other formats for later use or analysis.
This chapter focuses on BeautifulSoup, a Python library for parsing HTML and XML documents that can extract data from web pages and is commonly used for web scraping and data mining.

BeautifulSoup
BeautifulSoup is a Python library for extracting data from web pages, particularly suited to parsing HTML and XML files.
BeautifulSoup provides a simple API for extracting and manipulating content in web pages, making it very suitable for web scraping and data extraction tasks.
Install BeautifulSoup
To use BeautifulSoup you need to install beautifulsoup4 and lxml or html.parser (an HTML parser).
We can use pip to install these dependencies:
pip install beautifulsoup4
pip install lxml # lxml is recommended as a parser (faster)
If you do not have lxml, you can use Python's built-in html.parser as the parser.
Basic Usage
BeautifulSoup parses HTML or XML data and provides methods to navigate, search and modify the parse tree.
Common BeautifulSoup operations include finding tags, getting tag attributes, extracting text, and so on.
To use BeautifulSoup, first import it and load the HTML page into a BeautifulSoup object.
Typically you first use a crawling library (such as requests) to get the web page content:
Example
from
bs4
import
BeautifulSoup
import
requests
Use requests to get the web page content
url
=
'https://cn.bing.com/'
Scrape the web page content of the Bing search engine
response
=
requests.
get
(
url
)
Use BeautifulSoup to parse the web page
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Use the lxml parser
Parse the web page content with the html.parser parser
soup = BeautifulSoup(response.text, 'html.parser')
Get the web page title:
Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://cn.bing.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
Make sure the request succeeded
if
response.
status_code
==
200
:
Use BeautifulSoup to parse the web page content
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Find
tag
title_tag
=
soup.
find
(
'title'
)
Print the title text
if
title_tag:
print
(
title_tag.
get_text
(
)
)
else
:
print
(
"Not found
tag"
)
else
:
print
(
"Request failed, status code:"
,
response.
status_code
)
Running the above code outputs the title as:
Search - Microsoft Bing
Chinese garbled-text issues
When using the requests library to fetch Chinese web pages, you may encounter encoding problems that prevent Chinese content from displaying correctly. To fetch and display Chinese web pages correctly, you usually need to handle the character encoding of the page.
Automatic encoding detection: requests usually infers the encoding of a page from the Content-Type response header, but this can sometimes be inaccurate; in that case you can use chardet to detect the encoding automatically.
Example
import
requests
url
=
'https://cn.bing.com/'
response
=
requests.
get
(
url
)
Use chardet to detect the encoding automatically
import
chardet
encoding
=
chardet.
detect
(
response.
content
)
[
'encoding'
]
print
(
encoding
)
response.
encoding
=
encoding
Running the above code produces the following output:
utf-8
If you know the encoding of the page (for example utf-8 or gbk), you can set response.encoding directly:
response.encoding = 'utf-8' # or 'gbk', choose as appropriate
Finding tags
BeautifulSoup provides several methods for finding tags in a web page; the most commonly used are find() and find_all().
find() returns the first matching tag
find_all() returns all matching tags
Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Find the first tag
first_link
=
soup.
find
(
'a'
)
print
(
first_link
)
print
(
"----------------------------"
)
Get the first href attribute of the tag
first_link_url
=
first_link.
get
(
'href'
)
print
(
first_link_url
)
print
(
"----------------------------"
)
Find all tag
all_links
=
soup.
find_all
(
'a'
)
print
(
all_links
)
The output is similar to the following:
News
----------------------------
http://news.baidu.com
----------------------------
[News, hao123, Maps, Videos,
Getting the text of a tag
With the get_text() method you can extract the text content inside a tag:
Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Get the first
text content of the tag
paragraph_text
=
soup.
find
(
'p'
)
.
get_text
(
)
Get all the text content on the page
all_text
=
soup.
get_text
(
)
print
(
all_text
)
The output is similar to the following:
Baidu it, you'll know
...
Finding child and parent tags
You can use
parent
and
children
attributes to access the parent and children of a tag:
# Get the parent tag of the current tag
parent_tag = first_link.parent
# Get all child tags of the current tag
children = first_link.children
Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Find the first tag
first_link
=
soup.
find
(
'a'
)
print
(
first_link
)
print
(
"----------------------------"
)
Get the parent tag of the current tag
parent_tag
=
first_link.
parent
print
(
parent_tag.
get_text
(
)
)
The output is similar to the following:
News
----------------------------
News hao123 Maps Videos Tieba Login More Products
Finding tags with specific attributes
You can find tags with specific attributes by passing those attributes.
For example, find all div tags with the class name example-class:
# Find all div tags with class="example-class" tag
divs_with_class = soup.find_all('div', class_='example-class')
# Find the p tag with id="unique-id" tag
unique_paragraph = soup.find('p', id='unique-id')
Get the search button whose id is su:

Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Find the one with id="unique-id" tag
unique_input
=
soup.
find
(
'input'
,
id
=
'su'
)
input_value
=
unique_input
[
'value'
]
Get the value of the input box
print
(
input_value
)
The output is:
Baidu it
Advanced usage
CSS selectors
BeautifulSoup also supports finding tags through CSS selectors.
The select() method lets you find tags using jQuery-like selector syntax:
# Use CSS selectors to find all div tags with class 'example' tag
example_divs = soup.select('div.example')
# Find all div tags href attribute in the tag
links = soup.select('a[href]')
Handling nested tags
BeautifulSoup supports deeply nested HTML structures; you can handle them by recursively finding child tags:
# Find nested div tags tag
nested_divs = soup.find_all('div', class_='nested')
for div in nested_divs:
print(div.get_text())
Modifying web page content
BeautifulSoup lets you modify HTML content.
We can modify the attributes and text of a tag, or delete tags:
Example
Modify the first href attribute of the tag
first_link
[
'href'
]
=
'http://new-url.com'
Modify the first
text content of the tag
first_paragraph
=
soup.
find
(
'p'
)
first_paragraph.
string
=
'Updated content'
Delete a tag
first_paragraph.
decompose
(
)
Convert to a string
You can convert a parsed BeautifulSoup object back into an HTML string:
# Convert to string
html_str = str(soup)
BeautifulSoup attributes and methods
The following are commonly used attributes and methods in BeautifulSoup:
Method/attribute Description Example
BeautifulSoup()Parse an HTML or XML document and return a BeautifulSoup object. soup = BeautifulSoup(html_doc, 'html.parser')
.prettify()Format and prettify the document content, producing a structured string. print(soup.prettify())
.find()Find the first matching tag. tag = soup.find('a')
.find_all()Find all matching tags and return a list. tags = soup.find_all('a')
.find_all_next()Find all matching tags after the current tag. tags = soup.find('div').find_all_next('p')
.find_all_previous()Find all matching tags before the current tag. tags = soup.find('div').find_all_previous('p')
.find_parent()Return the parent tag of the current tag. parent = tag.find_parent()
.find_all_parents()Find all parent tags of the current tag. parents = tag.find_all_parents()
.find_next_sibling()Find the next sibling tag of the current tag. next_sibling = tag.find_next_sibling()
.find_previous_sibling()Find the previous sibling tag of the current tag. prev_sibling = tag.find_previous_sibling()
.parentGet the parent tag of the current tag. parent = tag.parent
.next_siblingGet the next sibling tag of the current tag. next_sibling = tag.next_sibling
.previous_siblingGet the previous sibling tag of the current tag. prev_sibling = tag.previous_sibling
.get_text()Extract the text content inside a tag, ignoring all HTML tags. text = tag.get_text()
.attrsReturn all attributes of a tag as a dictionary. href = tag.attrs['href']
.stringGet the string content inside a tag. string_content = tag.string
.nameReturn the name of the tag. tag_name = tag.name
.contentsReturn all child elements of the tag as a list. children = tag.contents
.descendantsReturn all descendant elements of the tag as a generator. for child in tag.descendants: print(child)
.parentGet the parent tag of the current tag. parent = tag.parent
.previous_elementGet the previous element before the current tag (excluding text). prev_elem = tag.previous_element
.next_elementGet the next element after the current tag (excluding text). next_elem = tag.next_element
.decompose()Remove the current tag and its contents from the tree. tag.decompose()
.unwrap()Remove the tag itself, keeping only its child content. tag.unwrap()
.insert()Insert a new tag or text inside the tag. tag.insert(0, new_tag)
.insert_before()Insert a new tag before the current tag. tag.insert_before(new_tag)
.insert_after()Insert a new tag after the current tag. tag.insert_after(new_tag)
.extract()Delete the tag and return it. extracted_tag = tag.extract()
.replace_with()Replace the current tag and its contents. tag.replace_with(new_tag)
.has_attr()Check whether a tag has a specified attribute. if tag.has_attr('href'):
.get()Get the value of a specified attribute. href = tag.get('href')
.clear()Clear all contents of the tag. tag.clear()
.encode()Encode the content of the tag into a byte stream. encoded = tag.encode()
.is_empty_elementCheck whether a tag is an empty element (for example
, ![]()
, etc.). if tag.is_empty_element:
.is_ancestor_of()Check whether the current tag is an ancestor of a specified tag. if tag.is_ancestor_of(another_tag):
.is_descendant_of()Check whether the current tag is a descendant of a specified tag. if tag.is_descendant_of(another_tag):
Other attributes
Method/attribute Description Example
.styleGet the inline style of a tag.style = tag['style'] .idGet the tag's id attribute.id = tag['id'] .class_Get the tag's class attribute.class_name = tag['class'] .stringGet the string content inside a tag, ignoring other tags.content = tag.string .parentGet the parent element of a tag.parent = tag.parent
Others
Method/attribute
Description
Example
find_all(string)
Use a string to find matching tags.
tag = soup.find_all('div', class_='container')
find_all(id)
Find the specified id tags.
tag = soup.find_all(id='main')
find_all(attrs)
Find tags with a specified attribute.
tag = soup.find_all(attrs={"href": "http://example.com"})
title_tag
=
soup.
find
(
'title'
)
Print the title text
if
title_tag:
(
title_tag.
get_text
(
)
)
else
:
(
"Not found
)
else
:
(
"Request failed, status code:"
,
response.
status_code
)
Running the above code outputs the title as:
Search - Microsoft Bing
Chinese garbled-text issues
When using the requests library to fetch Chinese web pages, you may encounter encoding problems that prevent Chinese content from displaying correctly. To fetch and display Chinese web pages correctly, you usually need to handle the character encoding of the page.
Automatic encoding detection: requests usually infers the encoding of a page from the Content-Type response header, but this can sometimes be inaccurate; in that case you can use chardet to detect the encoding automatically.
Example
import
requests
url
=
'https://cn.bing.com/'
response
=
requests.
get
(
url
)
Use chardet to detect the encoding automatically
import
chardet
encoding
=
chardet.
detect
(
response.
content
)
[
'encoding'
]
(
encoding
)
response.
encoding
=
encoding
Running the above code produces the following output:
utf-8
If you know the encoding of the page (for example utf-8 or gbk), you can set response.encoding directly:
response.encoding = 'utf-8' # or 'gbk', choose as appropriate
Finding tags
BeautifulSoup provides several methods for finding tags in a web page; the most commonly used are find() and find_all().
find()returns the first matching tagfind_all()returns all matching tags
Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Find the first tag
first_link
=
soup.
find
(
'a'
)
(
first_link
)
(
"----------------------------"
)
Get the first href attribute of the tag
first_link_url
=
first_link.
get
(
'href'
)
(
first_link_url
)
(
"----------------------------"
)
Find all tag
all_links
=
soup.
find_all
(
'a'
)
(
all_links
)
The output is similar to the following:
News
----------------------------
http://news.baidu.com
----------------------------
[News, hao123, Maps, Videos,
Getting the text of a tag
With the get_text() method you can extract the text content inside a tag:
Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Get the first
text content of the tag
paragraph_text
=
soup.
find
(
'p'
)
.
get_text
(
)
Get all the text content on the page
all_text
=
soup.
get_text
(
)
(
all_text
)
The output is similar to the following:
Baidu it, you'll know
...
Finding child and parent tags
You can use
parent
and
children
attributes to access the parent and children of a tag:
# Get the parent tag of the current tag
parent_tag = first_link.parent
# Get all child tags of the current tag
children = first_link.children
Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Find the first tag
first_link
=
soup.
find
(
'a'
)
(
first_link
)
(
"----------------------------"
)
Get the parent tag of the current tag
parent_tag
=
first_link.
parent
(
parent_tag.
get_text
(
)
)
The output is similar to the following:
News
----------------------------
News hao123 Maps Videos Tieba Login More Products
Finding tags with specific attributes
You can find tags with specific attributes by passing those attributes.
For example, find all div tags with the class name example-class:
# Find all div tags with class="example-class" tag
divs_with_class = soup.find_all('div', class_='example-class')
# Find the p tag with id="unique-id" tag
unique_paragraph = soup.find('p', id='unique-id')
Get the search button whose id is su:

Example
from
bs4
import
BeautifulSoup
import
requests
Specify the website whose title you want to get
url
=
'https://www.baidu.com/'
Scrape the web page content of the Bing search engine
Send an HTTP request to get the web page content
response
=
requests.
get
(
url
)
Chinese garbled-text issues
response.
encoding
=
'utf-8'
soup
=
BeautifulSoup
(
response.
text
,
'lxml'
)
Find the one with id="unique-id" tag
unique_input
=
soup.
find
(
'input'
,
id
=
'su'
)
input_value
=
unique_input
[
'value'
]
Get the value of the input box
print
(
input_value
)
The output is:
Baidu it
Advanced usage
CSS selectors
BeautifulSoup also supports finding tags through CSS selectors.
The select() method lets you find tags using jQuery-like selector syntax:
# Use CSS selectors to find all div tags with class 'example' tag
example_divs = soup.select('div.example')
# Find all div tags href attribute in the tag
links = soup.select('a[href]')
Handling nested tags
BeautifulSoup supports deeply nested HTML structures; you can handle them by recursively finding child tags:
# Find nested div tags tag
nested_divs = soup.find_all('div', class_='nested')
for div in nested_divs:
print(div.get_text())
Modifying web page content
BeautifulSoup lets you modify HTML content.
We can modify the attributes and text of a tag, or delete tags:
Example
Modify the first href attribute of the tag
first_link
[
'href'
]
=
'http://new-url.com'
Modify the first
text content of the tag
first_paragraph
=
soup.
find
(
'p'
)
first_paragraph.
string
=
'Updated content'
Delete a tag
first_paragraph.
decompose
(
)
Convert to a string
You can convert a parsed BeautifulSoup object back into an HTML string:
# Convert to string
html_str = str(soup)
BeautifulSoup attributes and methods
The following are commonly used attributes and methods in BeautifulSoup:
Method/attribute Description Example
BeautifulSoup()Parse an HTML or XML document and return a BeautifulSoup object. soup = BeautifulSoup(html_doc, 'html.parser')
.prettify()Format and prettify the document content, producing a structured string. print(soup.prettify())
.find()Find the first matching tag. tag = soup.find('a')
.find_all()Find all matching tags and return a list. tags = soup.find_all('a')
.find_all_next()Find all matching tags after the current tag. tags = soup.find('div').find_all_next('p')
.find_all_previous()Find all matching tags before the current tag. tags = soup.find('div').find_all_previous('p')
.find_parent()Return the parent tag of the current tag. parent = tag.find_parent()
.find_all_parents()Find all parent tags of the current tag. parents = tag.find_all_parents()
.find_next_sibling()Find the next sibling tag of the current tag. next_sibling = tag.find_next_sibling()
.find_previous_sibling()Find the previous sibling tag of the current tag. prev_sibling = tag.find_previous_sibling()
.parentGet the parent tag of the current tag. parent = tag.parent
.next_siblingGet the next sibling tag of the current tag. next_sibling = tag.next_sibling
.previous_siblingGet the previous sibling tag of the current tag. prev_sibling = tag.previous_sibling
.get_text()Extract the text content inside a tag, ignoring all HTML tags. text = tag.get_text()
.attrsReturn all attributes of a tag as a dictionary. href = tag.attrs['href']
.stringGet the string content inside a tag. string_content = tag.string
.nameReturn the name of the tag. tag_name = tag.name
.contentsReturn all child elements of the tag as a list. children = tag.contents
.descendantsReturn all descendant elements of the tag as a generator. for child in tag.descendants: print(child)
.parentGet the parent tag of the current tag. parent = tag.parent
.previous_elementGet the previous element before the current tag (excluding text). prev_elem = tag.previous_element
.next_elementGet the next element after the current tag (excluding text). next_elem = tag.next_element
.decompose()Remove the current tag and its contents from the tree. tag.decompose()
.unwrap()Remove the tag itself, keeping only its child content. tag.unwrap()
.insert()Insert a new tag or text inside the tag. tag.insert(0, new_tag)
.insert_before()Insert a new tag before the current tag. tag.insert_before(new_tag)
.insert_after()Insert a new tag after the current tag. tag.insert_after(new_tag)
.extract()Delete the tag and return it. extracted_tag = tag.extract()
.replace_with()Replace the current tag and its contents. tag.replace_with(new_tag)
.has_attr()Check whether a tag has a specified attribute. if tag.has_attr('href'):
.get()Get the value of a specified attribute. href = tag.get('href')
.clear()Clear all contents of the tag. tag.clear()
.encode()Encode the content of the tag into a byte stream. encoded = tag.encode()
.is_empty_elementCheck whether a tag is an empty element (for example
, ![]()
, etc.). if tag.is_empty_element:
.is_ancestor_of()Check whether the current tag is an ancestor of a specified tag. if tag.is_ancestor_of(another_tag):
.is_descendant_of()Check whether the current tag is a descendant of a specified tag. if tag.is_descendant_of(another_tag):
Other attributes
Method/attribute Description Example
.styleGet the inline style of a tag.style = tag['style'] .idGet the tag's id attribute.id = tag['id'] .class_Get the tag's class attribute.class_name = tag['class'] .stringGet the string content inside a tag, ignoring other tags.content = tag.string .parentGet the parent element of a tag.parent = tag.parent
Others
Method/attribute
Description
Example
find_all(string)
Use a string to find matching tags.
tag = soup.find_all('div', class_='container')
find_all(id)
Find the specified id tags.
tag = soup.find_all(id='main')
find_all(attrs)
Find tags with a specified attribute.
tag = soup.find_all(attrs={"href": "http://example.com"})