from bs4 import BeautifulSoup
45 Beautiful Soup (Basic)
= """<html><head><title>The Dormouse's story</title></head>
html_doc <body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
= BeautifulSoup(html_doc, 'html.parser')
soup
print(soup.prettify())
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
<body>
<p class="title">
<b>
The Dormouse's story
</b>
</p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link3">
Tillie
</a>
;
and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
45.1 Basic Usage
45.1.1 Title
soup.title
<title>The Dormouse's story</title>
soup.title.name
'title'
soup.title.string
"The Dormouse's story"
soup.title.parent.name
'head'
45.1.2 Paragraph
soup.p
<p class="title"><b>The Dormouse's story</b></p>
'class'] soup.p[
['title']
45.1.3 Links
soup.a
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
soup.a
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
'a') soup.find_all(
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
id="link3") soup.find(
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
45.2 Tasks
45.2.1 Extracting all the URLs
Extracting all the URLs found within a page’s <a>
tags:
for link in soup.find_all('a'):
print(link.get('href'))
http://example.com/elsie
http://example.com/lacie
http://example.com/tillie
"href") for link in soup.find_all('a')] [link.get(
['http://example.com/elsie',
'http://example.com/lacie',
'http://example.com/tillie']
for link in soup.find_all('a')] [link.name
['a', 'a', 'a']
for link in soup.find_all('a')] [link.string
['Elsie', 'Lacie', 'Tillie']
45.2.2 Extract all Text
Extracting all the text from a page:
soup.get_text()
"The Dormouse's story\n\nThe Dormouse's story\nOnce upon a time there were three little sisters; and their names were\nElsie,\nLacie and\nTillie;\nand they lived at the bottom of a well.\n...\n"