Beautiful Soup的用法(五):select的使用
阿新 • • 發佈:2019-01-24
select
的功能跟find
和find_all
一樣用來選取特定的標籤,它的選取規則依賴於css
,我們把它叫做css選擇器
,如果之前有接觸過jquery
,可以發現select
的選取規則和jquery
有點像。
通過標籤名查詢
在進行過濾時標籤名不加任何修飾,如下:
from bs4 import BeautifulSoup import re html = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> </body> </html> """ soup = BeautifulSoup(html, "lxml") print soup.select('p')
返回的結果如下:
[<p class="title" name="dromouse"><b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little sisters; and their names were\n<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and\n<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;\nand they lived at the bottom of a well.</p>]
通過結果可以看出,他返回的是一個數組,再繼續看看數組裡的元素是什麼呢?
print type(soup.select('p')[0])
結果為:
<class 'bs4.element.Tag'>
清楚了返回的是bs4.element.Tag
,這一點和find_all是一樣的,select('p')
返回了 所有標籤名為p的tag。
通過類名和id進行查詢
在進行過濾時類名前加點,id名前加 #
print soup.select('.title')
print soup.select('#link2')
返回的結果為:
[<p class="title" name="dromouse"><b>The Dormouse's story</b></p>] [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
通過屬性查詢
如果不是id或者是類名,是不是就不能進行過濾了?如果可以,該如何來表達,
print soup.select('[href="http://example.com/lacie"]')
選擇href
為http://example.com/lacie
的tag。
組合查詢
組合查詢可以分為兩種,一種是在一個tag中進行兩個條件的查詢,一種是樹狀的查詢一層一層之間的查詢。
第一種情況,如下所示:
print soup.select('a#link2')
選擇標籤名為a
,id
為link2
的tag。
輸出的結果如下:
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
另一種情況,如下:
從body
開始,在body
裡面查詢 所有的 p
,在所有的p
中查詢 標籤名為a
,id
為link2的tag,這樣像樹狀一層一層的查詢,在分析html
結構是是非常常見的。層和層之間用空格分開。
print soup.select('body p a#link2')
結果如下:
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
更多教程:阿貓學程式設計