網頁解析器的目的 及 四種網頁解析器的類型:
結構化解析——DOM(Document Object Model) 樹。結構如下:
網頁解析器 - Beautiful Soup - 基本語法 ↓↓↓↓↓ 【Beautiful Soup技術文檔】
1.創建BeautifulSoup對象:↓↓↓↓
from bs4 import BeautifulSoup
#根據HTML網頁字符串創建BeautifulSoup對象
soup = BeautifulSoup(
html_doc, #html文檔字符串
'html.parser' #html解析器
from_encoding='utf8' #html文檔的編碼
)
2.搜索節點(find_all,find):↓↓↓↓
#方法:find_all(name,attrs,string)
#查找所有標籤爲a的節點
soup.find_all('a')
#查找所有標籤爲a,連接符合/view/123.htm形式的節點
soup.find_all('a',href='/view/123.htm')
soup.find_all('a',href=re.compile(r'/view/\d+\.htm')) #支持正則表達進行匹配內容
#查找所有標籤爲div,class爲abc,文字爲Python的節點。
soup.find_all('div',class_=‘abc’,string='Python') #class加下劃線,是因爲python的關鍵字有class,避免衝突
3.訪問節點信息:↓↓↓↓
#得到節點:<a herf='1.html'>Python</a>
#獲取查找到的節點的標籤名稱
node.name
#獲取查找到的節點的href屬性
node['herf']
#獲取查找到的節點的鏈接文字
node.get_text()
實例測試: