【python爬蟲專項(4)】BeautifulSoup介紹、安裝以及簡單使用

1. BeautifulSoup介紹與安裝

1.1 什麼是BeautifulSoup

Beautiful Soup 是一個可以從HTML或XML文件中提取數據的Python庫.它能夠通過轉換器實現慣用的文檔導航,查找,修改文檔的方式

1.2 如何安裝?

首先查看電腦中有沒有BeautifulSoup工具包:pip show beautifulsoup4
在這裏插入圖片描述
直接安裝:pip install beautifulsoup4

1.3 如何導入BeaitufulSoup?

在代碼窗口頂部輸入: from bs4 import BeautifulSoup

1.4 官方案例演示

設置變量,輸入以下html內容​,代碼如下

h = """
<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 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>
"""


soup = BeautifulSoup(h,'lxml')

print(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>

解析標籤

查找title標籤 soup.title
輸出title標籤的名字 soup.title.name
查找p標籤 soup.p
輸出p標籤中屬性class的內容 soup.p[‘class’]
查找a標籤 soup.a/soup.find(‘a’)
查找所有a標籤 soup.find_all(‘a’)

查找title標籤

print(soup.title)

#輸出爲:
<title>The Dormouse's story</title>

輸出title標籤的名字

print(soup.title.name)

#輸出爲:
'tltle'

查找p標籤

print(soup.p)

#輸出爲
<p class="title"><b>The Dormouse's story</b></p>

輸出p標籤中屬性class的內容

print(soup.p['class'])

#輸出爲
['title']

查找a標籤

print(soup.a)
print(soup.find('a'))

#輸出爲
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

查找所有a標籤

print(soup.find_all('a'))

#輸出爲
[<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>]

直接使用soup.tag(標籤)的輸出結果和使用soup.find(‘tag’)的輸出結果是一樣的,而且都是 <class ‘bs4.element.Tag’>數據類型

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章