Beautiful Soup是用Python寫的一個HTML/XML的解析器,它可以很好的處理不規(guī)范標(biāo)記并生成剖析樹(parse tree)。 它提供簡單又常用的導(dǎo)航(navigating),搜索以及修改剖析樹的操作。它可以大大節(jié)省你的編程時間。
Beautiful Soup介紹:
1.Beautiful Soup提供了一些簡單的方法和Python術(shù)語,用于檢索和修改語法樹:一個用于解析文檔并提取相關(guān)信息的工具包。這樣你寫一個應(yīng)用不需要寫很多代碼。
2.Beautiful Soup自動將輸入文檔轉(zhuǎn)換為Unicode編碼,并將輸出文檔轉(zhuǎn)化為UTF-8編碼。你不需要考慮編碼,除非輸入文檔沒有指出其編碼并且Beautiful Soup無法自動檢測到,這時你需要指出原來的編碼方式。
3.Beautiful Soup位于一些流行的Python解析器比如lxml和html5lib的上層,這允許你使用不同的解析策略或者犧牲速度來換取靈活性。
如何遍歷樹?
使用find_all 函數(shù)
find_all(name, attrs, recursive, text, limit, **kwargs)
舉例說明:
print soup.find_all('title')
print soup.find_all('p','title')
print soup.find_all('a')
print soup.find_all(id="link2")
print soup.find_all(id=True)
返回值為:
[<title>The Dormouse's story</title>]
[<p class="title"><b>The Dormouse's story</b></p>]
[<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>]
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</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>]
使用方法:
1.下載完成之后需要解壓縮,假設(shè)放到D:/python下。
2.運行cmd,切換到D:/python/beautifulsoup4-4.3.2/目錄下(根據(jù)自己解壓縮后的目錄和下載的版本號修改),cd /d D:/python//beautifulsoup4-4.3.2
3.運行命令:
setup.py build
setup.py install
4.在IDE下from bs4 import BeautifulSoup,沒有報錯說明安裝成功。