python 理解Beautiful Soup庫的基本元素
阿新 • • 發佈:2018-12-09
理解Beautiful Soup的基本元素是理解Beautiful Soup庫的基礎。
首先我們說明一下Beautiful Soup庫能幹什麼。
我們以開啟html檔案為例。
任何一組html檔案它都是以尖括號為組的標籤組織起來的。而這些標籤建立起來的東西我們稱之為標籤樹。
而Beautiful Soup庫是解析,遍歷,維護標籤樹的功能庫。
標籤的具體格式如圖:
Beautiful Soup庫常見的四種解析器:
現在我們來介紹一下Beautiful Soup庫的基本元素:
下面我們來介紹一下獲得tag標籤的相關方法
任何語法標籤都可以用soup.tag方法訪問獲得,比如我們要獲取某個介面的a標籤:
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, "html.parser")
tag = soup.a
print(tag)
輸出為:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
但是當存在多個標籤的時候,我們用soup.tag只能返回其中第一個。
name表示獲取相關標籤的名字,比如:
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, "html.parser")
print(soup.a.parent.name)
print(soup.a.parent.parent.name)
輸出為:
p
body
標籤的屬性Attributes是在標籤中表明標籤特點的相關區域。
舉個例子:
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, "html.parser")
tag = soup.a
print(tag.attrs)
輸出:
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
我們再來看一下comment型別。
在html5介面中 我們用<!--abc-->表示註釋abc,而comment標籤可以表示字串中被註釋的部分。
如:
from bs4 import BeautifulSoup
newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is"
"not a comment</p>","html.parser")
print(type(newsoup.b.string))
print(type(newsoup.p.string))
輸出:
<class 'bs4.element.Comment'>
<class 'bs4.element.NavigableString'>
不過這個comment在bs4裡面並不常用。