Python爬蟲學習:Beautiful Soup (1)

“美味的雞湯”,是一個可以從HTML或XML文件中提取 數據的Python庫。它能夠通過你喜歡的轉換器實現常規的文檔導航,查找,修改文檔的操作。Beautiful Soup會幫你節省數小時甚至數天的工作時間。

1. 安裝Beautiful Soup

點擊查看

2. 解析器

解析器 使用方法 優勢 劣勢
Python標準庫 BeautifulSoup(markup,"html.parser") Python的內置標準庫/執行速度適中/文檔容錯能力強 Python2.7.3及Python3.22之前的版本文檔容錯能力差
lxml HTML 解析器 BeautifulSoup(markup,"lxml") 速度快,文檔容錯能力強 需要安裝C語言庫
lxml XML解析器 BeautifulSoup(markup,"xml") 速度快,唯一支持XML的解析器 需要安裝C語言庫
html5lib BeautifulSoup(markup,"html5lib") 最好的容錯性,以瀏覽器的方式解析文檔,生成HTML5格式的文檔 速度慢,不依賴外部擴展

3. 基本用法

from bs4 import BeautifulSoup
html = """
<html>
<head><title>The test!</title></head>
<body>
<ol>
<li><a href="https://blog.csdn.net/nanhuaibeian/article/details/89020249" rel="nofollow" target="_blank">入門</a></li>
<li><a href="https://blog.csdn.net/nanhuaibeian/article/details/89075453" rel="nofollow" target="_blank">使用urllib(request)</a></li>
<li><a href="https://blog.csdn.net/nanhuaibeian/article/details/89163384" rel="nofollow" target="_blank">使用urllib(error)</a></li>
<li><a href="https://blog.csdn.net/nanhuaibeian/article/details/89166027" rel="nofollow" target="_blank">使用requests</a></li>
<li><a href="https://blog.csdn.net/nanhuaibeian/article/details/89041626" rel="nofollow" target="_blank">下載一隻貓</a></li>
<li><a href="https://blog.csdn.net/nanhuaibeian/article/details/89048805" rel="nofollow" target="_blank">翻譯文本</a></li>
</ol>
"""
soup = BeautifulSoup(html,'lxml')
print(soup.prettify())
print(soup.title.string)
#print(soup.title.text)

在這裏插入圖片描述

soup = BeautifulSoup(html,'lxml')

這裏第一個參數傳給BeautifulSoup對象,該對象的第二個參數爲解析器的類型,此時就完成了BeautifulSoup對象的初始化,然後將這個對象賦值給soup變量。
同時對於不標準的HTML字符串BeautifulSoup會自動更正格式

prettify()方法:將要解析的字符串以標準的縮進格式輸出

soup.title.string,實際上是輸出HTML中title節點的文本內容。所以soup.title可以選出HTML中的title節點,再調用string屬性就可以得到裏面的文本了。

直接調用節點的名稱就可以選擇節點元素,再調用string屬性就可以得到節點內的文本了
在這裏插入圖片描述
當又多個節點時,這種選擇方式只會選擇到第一個匹配的節點,其他的後面節點都會被忽略

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