beautifulsoup
一、簡介:
beautiful soup 是一個HTML XML 的解析庫,可以完成導航、收索、修改分析樹等功能
它自動將輸入的文檔轉換成 Unicode 編碼,輸出文檔轉換爲 UTF-8編碼
二、beautifulsoup支持的解析器
lxml HTML解析器 | BeautifulSoup(markup,“lxml”) | 速度快,文檔容錯能力強 |
---|---|---|
lxml XML解析器 | BeautifulSoup(markup,“xml”) | 速度快,唯一支持XML |
html5lib | BeautifulSoup(makeup,‘html5lib’) | 最好容錯性,以瀏覽器的方式解析文檔、生成HTML5格式的文檔 |
三、beautiful soup 對象的屬性
節點選擇器
html='''
<html><head><title>the dormouse's story </title></head>
<body>
<p class="title" name="dromouse"><b>the dormouse story</b></p>
<p class="story"> once up on a time there were three little sisters;and their names were
<a href="http://exampe.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://exampe.com/lacie" class="sister" id="link2">Lacie</a>and
<a href="http://exampe.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
'''
#創建Beautiful Soup 對象,並會自動補全html缺失的標籤
soup = BeautifulSoup(html,'lxml')
print(soup.title.name)#利用name屬性可以獲取節點的名稱#title
print(soup.p.attrs)#利用attrs獲取節點的屬性,Id,class 等等#字典形式{'class': ['title'], 'name': 'dromouse'}
print(soup.p['class'])#獲取字典中的值#['title']
print(soup.p.string)#利用 string 獲得節點內容#the dormouse story
name:節點名稱
attrs: 節點屬性 id class 等等獲取結果爲字典
string : 獲取節點內容
注意:屬性對應的爲第一個匹配值的結果
關聯選擇:
(1)子節點和子孫節點
contents屬性 獲取節點的直接字節點,既包含節點,又包含文本,最後會將他們以列表形式統一返回
調用childrens屬性時,返回結果是生成器類型
descendants 屬性,獲取所有的子孫節點
(2)父節點和祖先節點
parent 獲取某個節點的父節點(直接父節點以及其內部的內容)
parents 獲取所有的祖先節點
(3)兄弟節點(同級節點)
4個屬性
next_sibling和 previous_sibling分別獲取節點的下一個和上一個兄弟元素
next_siblings和 previous_sibling則分別返回所有後面和前面的兄弟節點的生成器
四、beautiful soup 對象的方法
1 find_all(name,attrs,recursive,text,**kwargs)
name : 根據節點名來查詢元素
attrs :根據屬性名來查詢
print(soup.find_all(attrs={'id':'list-1'}))
text 匹配節點的文本
text 參數可用來匹配節點的文本,傳入的形式可以是字符串,可以是正則表達式。
2 find()
只返回匹配的第一個元素
而find_all()返回的是所有匹配元素組成的列表
3 find_parents()和 find_parent()
前者返回所有的祖先節點,後者返回直接節點
4 find_next_siblings 和 find_next_sibling
前者返回前面的所有兄弟節點,後者返回前面的第一個兄弟節點
5 find_all_next()和find_next()
前者返回所有符號條件的節點,後者返回第一個符合條件的節點
6 find_all_previous()和find_previous
前者返回節點後所有符號條件的節點,後者返回第一個符合條件的節點
五、CSS選擇器
使用 css 選擇器時,只需要調用 select()方法,傳人相應的 css 選擇器即可
print(soup.select('ul li'))
print(soup.select('#list-2 .element'))
print(soup.select('ul')[0])
返回的結果均是符合 css 選擇器的節點組成的列表。
例如, select(‘ul li’)則是選擇所有 ul 節點下面的所有 li 節點,結果便是所有的 li 節點組成的列表
支持遍歷
from bs4 import BeatifulSoup
soup = Beautiful(html,'lxml')
for ul in soup.select('ul'):
print(ul.select('li'))
正常輸出了所有 ul 節點下所有 li 節點組成的列表。
summary:
節點選擇篩選器功能弱,但是速度快
如果對CSS選擇器熟悉的話,可以使用select()方法選擇
看來要去學一下前端三件套了
HTML,一個標籤裏的內容