Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Web Scraping - BeautifulSoup

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:

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</h1> <p>    title_tag</p> <p>=</p> <p>soup.</p> <p>find</p> <p>(</p> <p>'title'</p> <p>)</p> <p>   </p> <p>   </p> <h1>Print the title text</h1> <p>   </p> <p>if</p> <p>title_tag:</p> <p>       </p> <p>print</p> <p>(</p> <p>title_tag.</p> <p>get_text</p> <p>(</p> <p>)</p> <p>)</p> <p>   </p> <p>else</p> <p>:</p> <p>       </p> <p>print</p> <p>(</p> <p>"Not found<title>tag"</p> <p>)</p> <p>else</p> <p>:</p> <p>   </p> <p>print</p> <p>(</p> <p>"Request failed, status code:"</p> <p>,</p> <p>response.</p> <p>status_code</p> <p>)</p> <p>Running the above code outputs the title as:</p> <pre><code> Search - Microsoft Bing </code></pre> <h3>Chinese garbled-text issues</h3> <p>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.</p> <p>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.</p> <h2>Example</h2> <p>import</p> <p>requests</p> <p>url</p> <p>=</p> <p>'https://cn.bing.com/'</p> <p>response</p> <p>=</p> <p>requests.</p> <p>get</p> <p>(</p> <p>url</p> <p>)</p> <h1>Use chardet to detect the encoding automatically</h1> <p>import</p> <p>chardet</p> <p>encoding</p> <p>=</p> <p>chardet.</p> <p>detect</p> <p>(</p> <p>response.</p> <p>content</p> <p>)</p> <p>[</p> <p>'encoding'</p> <p>]</p> <p>print</p> <p>(</p> <p>encoding</p> <p>)</p> <p>response.</p> <p>encoding</p> <p>=</p> <p>encoding</p> <p>Running the above code produces the following output:</p> <pre><code> utf-8 </code></pre> <p>If you know the encoding of the page (for example utf-8 or gbk), you can set response.encoding directly:</p> <pre><code> response.encoding = 'utf-8' # or 'gbk', choose as appropriate </code></pre> <h3>Finding tags</h3> <p>BeautifulSoup provides several methods for finding tags in a web page; the most commonly used are find() and find_all().</p> <ul> <li><code>find()</code> returns the first matching tag</li> <li><code>find_all()</code> returns all matching tags</li> </ul> <h2>Example</h2> <p>from</p> <p>bs4</p> <p>import</p> <p>BeautifulSoup</p> <p>import</p> <p>requests</p> <h1>Specify the website whose title you want to get</h1> <p>url</p> <p>=</p> <p>'https://www.baidu.com/'</p> <h1>Scrape the web page content of the Bing search engine</h1> <h1>Send an HTTP request to get the web page content</h1> <p>response</p> <p>=</p> <p>requests.</p> <p>get</p> <p>(</p> <p>url</p> <p>)</p> <h1>Chinese garbled-text issues</h1> <p>response.</p> <p>encoding</p> <p>=</p> <p>'utf-8'</p> <p>soup</p> <p>=</p> <p>BeautifulSoup</p> <p>(</p> <p>response.</p> <p>text</p> <p>,</p> <p>'lxml'</p> <p>)</p> <h1>Find the first <a> tag</h1> <p>first_link</p> <p>=</p> <p>soup.</p> <p>find</p> <p>(</p> <p>'a'</p> <p>)</p> <p>print</p> <p>(</p> <p>first_link</p> <p>)</p> <p>print</p> <p>(</p> <p>"----------------------------"</p> <p>)</p> <h1>Get the first <a> href attribute of the tag</h1> <p>first_link_url</p> <p>=</p> <p>first_link.</p> <p>get</p> <p>(</p> <p>'href'</p> <p>)</p> <p>print</p> <p>(</p> <p>first_link_url</p> <p>)</p> <p>print</p> <p>(</p> <p>"----------------------------"</p> <p>)</p> <h1>Find all <a> tag</h1> <p>all_links</p> <p>=</p> <p>soup.</p> <p>find_all</p> <p>(</p> <p>'a'</p> <p>)</p> <p>print</p> <p>(</p> <p>all_links</p> <p>)</p> <p>The output is similar to the following:</p> <pre><code><a class="mnav" href="http://news.baidu.com" name="tj_trnews">News</a> ---------------------------- http://news.baidu.com ---------------------------- [<a class="mnav" href="http://news.baidu.com" name="tj_trnews">News</a>, <a class="mnav" href="https://www.hao123.com" name="tj_trhao123">hao123</a>, <a class="mnav" href="http://map.baidu.com" name="tj_trmap">Maps</a>, <a class="mnav" href="http://v.baidu.com" name="tj_trvideo">Videos</a>, </code></pre> <h3>Getting the text of a tag</h3> <p>With the get_text() method you can extract the text content inside a tag:</p> <h2>Example</h2> <p>from</p> <p>bs4</p> <p>import</p> <p>BeautifulSoup</p> <p>import</p> <p>requests</p> <h1>Specify the website whose title you want to get</h1> <p>url</p> <p>=</p> <p>'https://www.baidu.com/'</p> <h1>Scrape the web page content of the Bing search engine</h1> <h1>Send an HTTP request to get the web page content</h1> <p>response</p> <p>=</p> <p>requests.</p> <p>get</p> <p>(</p> <p>url</p> <p>)</p> <h1>Chinese garbled-text issues</h1> <p>response.</p> <p>encoding</p> <p>=</p> <p>'utf-8'</p> <p>soup</p> <p>=</p> <p>BeautifulSoup</p> <p>(</p> <p>response.</p> <p>text</p> <p>,</p> <p>'lxml'</p> <p>)</p> <h1>Get the first <p> text content of the tag</h1> <p>paragraph_text</p> <p>=</p> <p>soup.</p> <p>find</p> <p>(</p> <p>'p'</p> <p>)</p> <p>.</p> <p>get_text</p> <p>(</p> <p>)</p> <h1>Get all the text content on the page</h1> <p>all_text</p> <p>=</p> <p>soup.</p> <p>get_text</p> <p>(</p> <p>)</p> <p>print</p> <p>(</p> <p>all_text</p> <p>)</p> <p>The output is similar to the following:</p> <pre><code> Baidu it, you'll know ... </code></pre> <h3>Finding child and parent tags</h3> <p>You can use</p> <p>parent</p> <p>and</p> <p>children</p> <p>attributes to access the parent and children of a tag:</p> <pre><code># 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 </code></pre> <h2>Example</h2> <p>from</p> <p>bs4</p> <p>import</p> <p>BeautifulSoup</p> <p>import</p> <p>requests</p> <h1>Specify the website whose title you want to get</h1> <p>url</p> <p>=</p> <p>'https://www.baidu.com/'</p> <h1>Scrape the web page content of the Bing search engine</h1> <h1>Send an HTTP request to get the web page content</h1> <p>response</p> <p>=</p> <p>requests.</p> <p>get</p> <p>(</p> <p>url</p> <p>)</p> <h1>Chinese garbled-text issues</h1> <p>response.</p> <p>encoding</p> <p>=</p> <p>'utf-8'</p> <p>soup</p> <p>=</p> <p>BeautifulSoup</p> <p>(</p> <p>response.</p> <p>text</p> <p>,</p> <p>'lxml'</p> <p>)</p> <h1>Find the first <a> tag</h1> <p>first_link</p> <p>=</p> <p>soup.</p> <p>find</p> <p>(</p> <p>'a'</p> <p>)</p> <p>print</p> <p>(</p> <p>first_link</p> <p>)</p> <p>print</p> <p>(</p> <p>"----------------------------"</p> <p>)</p> <h1>Get the parent tag of the current tag</h1> <p>parent_tag</p> <p>=</p> <p>first_link.</p> <p>parent</p> <p>print</p> <p>(</p> <p>parent_tag.</p> <p>get_text</p> <p>(</p> <p>)</p> <p>)</p> <p>The output is similar to the following:</p> <pre><code><a class="mnav" href="http://news.baidu.com" name="tj_trnews">News</a> ---------------------------- News hao123 Maps Videos Tieba Login More Products </code></pre> <h3>Finding tags with specific attributes</h3> <p>You can find tags with specific attributes by passing those attributes.</p> <p>For example, find all div tags with the class name example-class:</p> <pre><code># Find all div tags with class="example-class" <div> tag divs_with_class = soup.find_all('div', class_='example-class') # Find the p tag with id="unique-id" <p> tag unique_paragraph = soup.find('p', id='unique-id') </code></pre> <p>Get the search button whose id is su:</p> <p><img src="https://www.runoob.com/wp-content/uploads/2024/12/2d889eb3-9562-45d6-9688-f7250252d3a8.png" alt="" /></p> <h2>Example</h2> <p>from</p> <p>bs4</p> <p>import</p> <p>BeautifulSoup</p> <p>import</p> <p>requests</p> <h1>Specify the website whose title you want to get</h1> <p>url</p> <p>=</p> <p>'https://www.baidu.com/'</p> <h1>Scrape the web page content of the Bing search engine</h1> <h1>Send an HTTP request to get the web page content</h1> <p>response</p> <p>=</p> <p>requests.</p> <p>get</p> <p>(</p> <p>url</p> <p>)</p> <h1>Chinese garbled-text issues</h1> <p>response.</p> <p>encoding</p> <p>=</p> <p>'utf-8'</p> <p>soup</p> <p>=</p> <p>BeautifulSoup</p> <p>(</p> <p>response.</p> <p>text</p> <p>,</p> <p>'lxml'</p> <p>)</p> <h1>Find the one with id="unique-id" <input> tag</h1> <p>unique_input</p> <p>=</p> <p>soup.</p> <p>find</p> <p>(</p> <p>'input'</p> <p>,</p> <p>id</p> <p>=</p> <p>'su'</p> <p>)</p> <p>input_value</p> <p>=</p> <p>unique_input</p> <p>[</p> <p>'value'</p> <p>]</p> <h1>Get the value of the input box</h1> <p>print</p> <p>(</p> <p>input_value</p> <p>)</p> <p>The output is:</p> <pre><code>Baidu it </code></pre> <hr /> <h2>Advanced usage</h2> <h3>CSS selectors</h3> <p>BeautifulSoup also supports finding tags through CSS selectors.</p> <p>The select() method lets you find tags using jQuery-like selector syntax:</p> <pre><code># Use CSS selectors to find all div tags with class 'example' <div> tag example_divs = soup.select('div.example') # Find all div tags <a> href attribute in the tag links = soup.select('a[href]') </code></pre> <h3>Handling nested tags</h3> <p>BeautifulSoup supports deeply nested HTML structures; you can handle them by recursively finding child tags:</p> <pre><code># Find nested div tags <div> tag nested_divs = soup.find_all('div', class_='nested') for div in nested_divs: print(div.get_text()) </code></pre> <h3>Modifying web page content</h3> <p>BeautifulSoup lets you modify HTML content.</p> <p>We can modify the attributes and text of a tag, or delete tags:</p> <h2>Example</h2> <h1>Modify the first <a> href attribute of the tag</h1> <p>first_link</p> <p>[</p> <p>'href'</p> <p>]</p> <p>=</p> <p>'http://new-url.com'</p> <h1>Modify the first <p> text content of the tag</h1> <p>first_paragraph</p> <p>=</p> <p>soup.</p> <p>find</p> <p>(</p> <p>'p'</p> <p>)</p> <p>first_paragraph.</p> <p>string</p> <p>=</p> <p>'Updated content'</p> <h1>Delete a tag</h1> <p>first_paragraph.</p> <p>decompose</p> <p>(</p> <p>)</p> <h3>Convert to a string</h3> <p>You can convert a parsed BeautifulSoup object back into an HTML string:</p> <pre><code> # Convert to string html_str = str(soup) </code></pre> <hr /> <h2>BeautifulSoup attributes and methods</h2> <p>The following are commonly used attributes and methods in BeautifulSoup:</p> <table> <thead> <tr><th><strong>Method/attribute</strong></th><th><strong>Description</strong></th><th><strong>Example</strong></th></tr> </thead> <tbody> <tr><td><code>BeautifulSoup()</code></td><td>Parse an HTML or XML document and return a BeautifulSoup object.</td><td><code>soup = BeautifulSoup(html_doc, 'html.parser')</code></td></tr> <tr><td><code>.prettify()</code></td><td>Format and prettify the document content, producing a structured string.</td><td><code>print(soup.prettify())</code></td></tr> <tr><td><code>.find()</code></td><td>Find the first matching tag.</td><td><code>tag = soup.find('a')</code></td></tr> <tr><td><code>.find_all()</code></td><td>Find all matching tags and return a list.</td><td><code>tags = soup.find_all('a')</code></td></tr> <tr><td><code>.find_all_next()</code></td><td>Find all matching tags after the current tag.</td><td><code>tags = soup.find('div').find_all_next('p')</code></td></tr> <tr><td><code>.find_all_previous()</code></td><td>Find all matching tags before the current tag.</td><td><code>tags = soup.find('div').find_all_previous('p')</code></td></tr> <tr><td><code>.find_parent()</code></td><td>Return the parent tag of the current tag.</td><td><code>parent = tag.find_parent()</code></td></tr> <tr><td><code>.find_all_parents()</code></td><td>Find all parent tags of the current tag.</td><td><code>parents = tag.find_all_parents()</code></td></tr> <tr><td><code>.find_next_sibling()</code></td><td>Find the next sibling tag of the current tag.</td><td><code>next_sibling = tag.find_next_sibling()</code></td></tr> <tr><td><code>.find_previous_sibling()</code></td><td>Find the previous sibling tag of the current tag.</td><td><code>prev_sibling = tag.find_previous_sibling()</code></td></tr> <tr><td><code>.parent</code></td><td>Get the parent tag of the current tag.</td><td><code>parent = tag.parent</code></td></tr> <tr><td><code>.next_sibling</code></td><td>Get the next sibling tag of the current tag.</td><td><code>next_sibling = tag.next_sibling</code></td></tr> <tr><td><code>.previous_sibling</code></td><td>Get the previous sibling tag of the current tag.</td><td><code>prev_sibling = tag.previous_sibling</code></td></tr> <tr><td><code>.get_text()</code></td><td>Extract the text content inside a tag, ignoring all HTML tags.</td><td><code>text = tag.get_text()</code></td></tr> <tr><td><code>.attrs</code></td><td>Return all attributes of a tag as a dictionary.</td><td><code>href = tag.attrs['href']</code></td></tr> <tr><td><code>.string</code></td><td>Get the string content inside a tag.</td><td><code>string_content = tag.string</code></td></tr> <tr><td><code>.name</code></td><td>Return the name of the tag.</td><td><code>tag_name = tag.name</code></td></tr> <tr><td><code>.contents</code></td><td>Return all child elements of the tag as a list.</td><td><code>children = tag.contents</code></td></tr> <tr><td><code>.descendants</code></td><td>Return all descendant elements of the tag as a generator.</td><td><code>for child in tag.descendants: print(child)</code></td></tr> <tr><td><code>.parent</code></td><td>Get the parent tag of the current tag.</td><td><code>parent = tag.parent</code></td></tr> <tr><td><code>.previous_element</code></td><td>Get the previous element before the current tag (excluding text).</td><td><code>prev_elem = tag.previous_element</code></td></tr> <tr><td><code>.next_element</code></td><td>Get the next element after the current tag (excluding text).</td><td><code>next_elem = tag.next_element</code></td></tr> <tr><td><code>.decompose()</code></td><td>Remove the current tag and its contents from the tree.</td><td><code>tag.decompose()</code></td></tr> <tr><td><code>.unwrap()</code></td><td>Remove the tag itself, keeping only its child content.</td><td><code>tag.unwrap()</code></td></tr> <tr><td><code>.insert()</code></td><td>Insert a new tag or text inside the tag.</td><td><code>tag.insert(0, new_tag)</code></td></tr> <tr><td><code>.insert_before()</code></td><td>Insert a new tag before the current tag.</td><td><code>tag.insert_before(new_tag)</code></td></tr> <tr><td><code>.insert_after()</code></td><td>Insert a new tag after the current tag.</td><td><code>tag.insert_after(new_tag)</code></td></tr> <tr><td><code>.extract()</code></td><td>Delete the tag and return it.</td><td><code>extracted_tag = tag.extract()</code></td></tr> <tr><td><code>.replace_with()</code></td><td>Replace the current tag and its contents.</td><td><code>tag.replace_with(new_tag)</code></td></tr> <tr><td><code>.has_attr()</code></td><td>Check whether a tag has a specified attribute.</td><td><code>if tag.has_attr('href'):</code></td></tr> <tr><td><code>.get()</code></td><td>Get the value of a specified attribute.</td><td><code>href = tag.get('href')</code></td></tr> <tr><td><code>.clear()</code></td><td>Clear all contents of the tag.</td><td><code>tag.clear()</code></td></tr> <tr><td><code>.encode()</code></td><td>Encode the content of the tag into a byte stream.</td><td><code>encoded = tag.encode()</code></td></tr> <tr><td><code>.is_empty_element</code></td><td>Check whether a tag is an empty element (for example <code><br></code>, <code><img></code>, etc.).</td><td><code>if tag.is_empty_element:</code></td></tr> <tr><td><code>.is_ancestor_of()</code></td><td>Check whether the current tag is an ancestor of a specified tag.</td><td><code>if tag.is_ancestor_of(another_tag):</code></td></tr> <tr><td><code>.is_descendant_of()</code></td><td>Check whether the current tag is a descendant of a specified tag.</td><td><code>if tag.is_descendant_of(another_tag):</code></td></tr> </tbody> </table> <h3>Other attributes</h3> <table> <thead> <tr><th><strong>Method/attribute</strong></th><th><strong>Description</strong></th><th><strong>Example</strong></th></tr> </thead> .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"})