beautifulsoup教程
BeautifulSoup4是爬蟲必學的技能。BeautifulSoup最主要的功能是從網頁抓取數據,Beautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼。BeautifulSoup支持Python標准庫中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,則 Python 會使用 Python默認的解析器,lxml 解析器更加強大,速度更快,推薦使用lxml 解析器。
一、BeautifulSoup4簡介
BeautifulSoup4和 lxml 一樣,Beautiful Soup 也是一個HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 數據。
BeautifulSoup支持Python標准庫中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,則 Python 會使用 Python默認的解析器,lxml 解析器更加強大,速度更快,推薦使用lxml 解析器。
Beautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然后,你僅僅需要說明一下原始編碼方式就可以了。
二、BeautifulSoup4主要解析器,以及優缺點:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-8f6XgNXi-1598587320926)(beautifulsoup%E6%95%99%E7%A8%8B/4CD4F032-4D45-4F82-8C15-0C791A2C34CA.png)]
三、BeautifulSoup4簡單使用
假設有這樣一個Html,具體內容如下:
1. <!DOCTYPE html> 2. <html> 3. 4. <head> 5. <meta content="text/html;charset=utf-8" http-equiv="content-type" /> 6. <meta content="IE=Edge" http-equiv="X-UA-Compatible" /> 7. <meta content="always" name="referrer" /> 8. <link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css" /> 9. <title>百度一下,你就知道 </title> 10. </head> 11. 12. <body link="#0000cc"> 13. <div id="wrapper"> 14. <div id="head"> 15. <div class="head_wrapper"> 16. <div id="u1"> 17. <a class="mnav" href="http://news.baidu.com" name="tj_trnews">新聞 </a> 18. <a class="mnav" href="https://www.hao123.com" name="tj_trhao123">hao123 </a> 19. <a class="mnav" href="http://map.baidu.com" name="tj_trmap">地圖 </a> 20. <a class="mnav" href="http://v.baidu.com" name="tj_trvideo">視頻 </a> 21. <a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">貼吧 </a> 22. <a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">更多產品 </a> 23. </div> 24. </div> 25. </div> 26. </div> 27. </body> 28. 29. </html>
創建beautifulsoup4對象:
1. from bs4 import BeautifulSoup 2. file = open('./aa.html', 'rb') 3. html = file.read() 4. bs = BeautifulSoup(html,"html.parser") # 縮進格式 5. 6. print(bs.prettify()) # 獲取title標簽的所有內容 7. print(bs.title) # 獲取title標簽的名稱 8. print(bs.title.name) # 獲取title標簽的文本內容 9. print(bs.title.string) # 獲取head標簽的所有內容 10. print(bs.head) # 獲取第一個div標簽中的所有內容 11. print(bs.div) # 獲取第一個div標簽的id的值 12. print(bs.div["id"]) # 獲取第一個a標簽中的所有內容 13. print(bs.a) # 獲取所有的a標簽中的所有內容 14. print(bs.find_all("a")) # 獲取id="u1" 15. print(bs.find(id="u1")) # 獲取所有的a標簽,並遍歷打印a標簽中的href的值 16. 17. for item in bs.find_all("a"): 18. print(item.get("href")) # 獲取所有的a標簽,並遍歷打印a標簽的文本值 19. 20. for item in bs.find_all("a"): 21. print(item.get_text())
四、BeautifulSoup4四大對象種類
BeautifulSoup4將復雜HTML文檔轉換成一個復雜的樹形結構,每個節點都是Python對象,所有對象可以歸納為4種:
- Tag
- NavigableString
- BeautifulSoup
- Comment
4.1 、Tag
Tag通俗點講就是HTML中的一個個標簽,例如:
1. from bs4 import BeautifulSoup 2. file = open('./aa.html', 'rb') 3. html = file.read() 4. bs = BeautifulSoup(html,"html.parser") 5. 6. # 獲取title標簽的所有內容 7. print(bs.title) 8. 9. # 獲取head標簽的所有內容 10. print(bs.head) 11. 12. # 獲取第一個a標簽的所有內容 13. print(bs.a) 14. 15. # 類型 16. print(type(bs.a))
我們可以利用 soup 加標簽名輕松地獲取這些標簽的內容,這些對象的類型是bs4.element.Tag。但是注意,它查找的是在所有內容中的第一個符合要求的標簽。
對於 Tag,它有兩個重要的屬性,是 name 和 attrs:
1. from bs4 import BeautifulSoup 2. file = open('./aa.html', 'rb') 3. html = file.read() 4. bs = BeautifulSoup(html,"html.parser") 5. 6. # [document] #bs 對象本身比較特殊,它的 name 即為 [document] 7. print(bs.name) 8. 9. # head #對於其他內部標簽,輸出的值便為標簽本身的名稱 10. print(bs.head.name) 11. 12. # 在這里,我們把 a 標簽的所有屬性打印輸出了出來,得到的類型是一個字典。 13. print(bs.a.attrs) 14. 15. #還可以利用get方法,傳入屬性的名稱,二者是等價的 16. print(bs.a['class']) # 等價 bs.a.get('class') 17. 18. # 可以對這些屬性和內容等等進行修改 19. bs.a['class'] = "newClass" 20. print(bs.a) 21. 22. # 還可以對這個屬性進行刪除 23. del bs.a['class'] 24. print(bs.a)
4.2、NavigableString
既然我們已經得到了標簽的內容,那么問題來了,我們要想獲取標簽內部的文字怎么辦呢?很簡單,用 .string 即可,例如:
1. from bs4 import BeautifulSoup 2. file = open('./aa.html', 'rb') 3. html = file.read() 4. 5. bs = BeautifulSoup(html,"html.parser") 6. 7. print(bs.title.string) 8. print(type(bs.title.string))
4.3、BeautifulSoup
BeautifulSoup對象表示的是一個文檔的內容。大部分時候,可以把它當作 Tag 對象,是一個特殊的 Tag,我們可以分別獲取它的類型,名稱,以及屬性,例如:
1. from bs4 import BeautifulSoup 2. file = open('./aa.html', 'rb') 3. html = file.read() 4. 5. bs = BeautifulSoup(html,"html.parser") 6. 7. print(type(bs.name)) 8. print(bs.name) 9. print(bs.attrs)
4.4、Comment
Comment 對象是一個特殊類型的 NavigableString 對象,其輸出的內容不包括注釋符號。
1. from bs4 import BeautifulSoup 2. file = open('./aa.html', 'rb') 3. html = file.read() 4. 5. bs = BeautifulSoup(html,"html.parser") 6. print(bs.a) 7. # 此時不能出現空格和換行符,a標簽如下: 8. # <a class="mnav" href="http://news.baidu.com" name="tj_trnews"><!--新聞--></a> 9. 10. print(bs.a.string) # 新聞 11. 12. print(type(bs.a.string)) # <class 'bs4.element.Comment'>
五、遍歷文檔樹
5.1、.contents:
獲取Tag的所有子節點,返回一個list
1. # tag的.content 屬性可以將tag的子節點以列表的方式輸出 2. print(bs.head.contents) 3. 4. # 用列表索引來獲取它的某一個元素 5. print(bs.head.contents[1])
5.2、.children:
獲取Tag的所有子節點,返回一個生成器
1. for child in bs.body.children: 2. print(child)
5.3、.descendants:獲取Tag的所有子孫節點
5.4、.strings:如果Tag包含多個字符串,即在子孫節點中有內容,可以用此獲取,而后進行遍歷
5.5、.stripped_strings:與strings用法一致,只不過可以去除掉那些多余的空白內容
5.6、.parent:獲取Tag的父節點
5.7、.parents:遞歸得到父輩元素的所有節點,返回一個生成器
5.8、.previous_sibling:獲取當前Tag的上一個節點,屬性通常是字符串或空白,真實結果是當前標簽與上一個標簽之間的頓號和換行符
5.9、.next_sibling:獲取當前Tag的下一個節點,屬性通常是字符串或空白,真是結果是當前標簽與下一個標簽之間的頓號與換行符
5.10、.previous_siblings:獲取當前Tag的上面所有的兄弟節點,返回一個生成器
5.11、.next_siblings:獲取當前Tag的下面所有的兄弟節點,返回一個生成器
5.12、.previous_element:獲取解析過程中上一個被解析的對象(字符串或tag),可能與previous_sibling相同,但通常是不一樣的
5.13、.next_element:獲取解析過程中下一個被解析的對象(字符串或tag),可能與next_sibling相同,但通常是不一樣的
5.14、.previous_elements:返回一個生成器,可以向前訪問文檔的解析內容
5.15、.next_elements:返回一個生成器,可以向后訪問文檔的解析內容
5.16、.has_attr:判斷Tag是否包含屬性
六、搜索文檔樹
6.1、find_all(name, attrs, recursive, text, **kwargs)
在上面的栗子中我們簡單介紹了find_all的使用,接下來介紹一下find_all的更多用法-過濾器。這些過濾器貫穿整個搜索API,過濾器可以被用在tag的name中,節點的屬性等。
(1)name參數:
字符串過濾:會查找與字符串完全匹配的內容
1. a_list = bs.find_all("a") 2. print(a_list)
正則表達式過濾:如果傳入的是正則表達式,那么BeautifulSoup4會通過search()來匹配內容
1. from bs4 import BeautifulSoup 2. import re 3. file = open('./aa.html', 'rb') 4. html = file.read() 5. 6. bs = BeautifulSoup(html,"html.parser") 7. 8. t_list = bs.find_all(re.compile("a")) 9. for item in t_list: 10. print(item)
列表:如果傳入一個列表,BeautifulSoup4將會與列表中的任一元素匹配到的節點返回
1. t_list = bs.find_all(["meta","link"]) 2. for item in t_list: 3. print(item)
方法:傳入一個方法,根據方法來匹配
1. from bs4 import BeautifulSoup 2. file = open('./aa.html', 'rb') 3. html = file.read() 4. 5. bs = BeautifulSoup(html,"html.parser") 6. 7. def name_is_exists(tag): 8. return tag.has_attr("name") 9. 10. t_list = bs.find_all(name_is_exists) 11. for item in t_list: 12. print(item)
(2)kwargs參數:
1. from bs4 import BeautifulSoup 2. import re 3. file = open('./aa.html', 'rb') 4. html = file.read() 5. 6. bs = BeautifulSoup(html,"html.parser") 7. 8. # 查詢id=head的Tag 9. t_list = bs.find_all(id="head") print(t_list) 10. 11. # 查詢href屬性包含ss1.bdstatic.com的Tag 12. t_list = bs.find_all(href=re.compile("http://news.baidu.com")) 13. print(t_list) 14. 15. # 查詢所有包含class的Tag(注意:class在Python中屬於關鍵字,所以加_以示區別) 16. t_list = bs.find_all(class_=True) 17. for item in t_list: 18. print(item)
(3)attrs參數:
並不是所有的屬性都可以使用上面這種方式進行搜索,比如HTML的data-*屬性:
t_list = bs.find_all(data-foo="value")
如果執行這段代碼,將會報錯。我們可以使用attrs參數,定義一個字典來搜索包含特殊屬性的tag:
1. t_list = bs.find_all(attrs={"data-foo":"value"}) 2. for item in t_list: 3. print(item)
(4)text參數:
通過text參數可以搜索文檔中的字符串內容,與name參數的可選值一樣,text參數接受 字符串,正則表達式,列表
1. from bs4 import BeautifulSoup 2. import re 3. file = open('./aa.html', 'rb') 4. html = file.read() 5. 6. bs = BeautifulSoup(html, "html.parser") 7. 8. t_list = bs.find_all(attrs={"data-foo": "value"}) 9. for item in t_list: 10. print(item) 11. 12. t_list = bs.find_all(text="hao123") 13. for item in t_list: 14. print(item) 15. 16. t_list = bs.find_all(text=["hao123", "地圖", "貼吧"]) 17. for item in t_list: 18. print(item) 19. 20. t_list = bs.find_all(text=re.compile("\d")) 21. for item in t_list: 22. print(item)
當我們搜索text中的一些特殊屬性時,同樣也可以傳入一個方法來達到我們的目的:
1. def length_is_two(text): 2. return text and len(text) == 2 3. 4. t_list = bs.find_all(text=length_is_two) 5. for item in t_list: 6. print(item)
(5)limit參數:
可以傳入一個limit參數來限制返回的數量,當搜索出的數據量為5,而設置了limit=2時,此時只會返回前2個數據
1. from bs4 import BeautifulSoup 2. import re 3. file = open('./aa.html', 'rb') 4. html = file.read() 5. 6. bs = BeautifulSoup(html, "html.parser") 7. 8. t_list = bs.find_all("a",limit=2) 9. for item in t_list: 10. print(item)
find_all除了上面一些常規的寫法,還可以對其進行一些簡寫:
1. # 兩者是相等的 2. # t_list = bs.find_all("a") => t_list = bs("a") 3. t_list = bs("a") # 兩者是相等的 4. # t_list = bs.a.find_all(text="新聞") => t_list = bs.a(text="新聞") 5. t_list = bs.a(text="新聞")
6.2、find()
find()將返回符合條件的第一個Tag,有時我們只需要或一個Tag時,我們就可以用到find()方法了。當然了,也可以使用find_all()方法,傳入一個limit=1,然后再取出第一個值也是可以的,不過未免繁瑣。
1. from bs4 import BeautifulSoup 2. import re 3. file = open('./aa.html', 'rb') 4. html = file.read() 5. 6. bs = BeautifulSoup(html, "html.parser") 7. 8. # 返回只有一個結果的列表 9. t_list = bs.find_all("title",limit=1) 10. print(t_list) 11. 12. # 返回唯一值 13. t = bs.find("title") 14. print(t) 15. 16. # 如果沒有找到,則返回None 17. t = bs.find("abc") print(t)
從結果可以看出find_all,盡管傳入了limit=1,但是返回值仍然為一個列表,當我們只需要取一個值時,遠不如find方法方便。但
是如果未搜索到值時,將返回一個None
在上面介紹BeautifulSoup4的時候,我們知道可以通過bs.div來獲取第一個div標簽,如果我們需要獲取第一個div下的第一個div,
我們可以這樣:
1. t = bs.div.div 2. 3. # 等價於 4. t = bs.find("div").find("div")
七、CSS選擇器
BeautifulSoup支持發部分的CSS選擇器,在Tag獲取BeautifulSoup對象的.select()方法中傳入字符串參數,即可使用CSS選擇器的語法找到Tag:
7.1、通過標簽名查找
1. print(bs.select('title')) 2. 3. print(bs.select('a'))
7.2、通過類名查找
1. print(bs.select('.mnav'))
7.3、通過id查找
1. print(bs.select('#u1'))
7.4、組合查找
1. print(bs.select('div .bri'))
7.5、屬性查找
1. print(bs.select('a[class="bri"]')) 2. print(bs.select('a[href="http://tieba.baidu.com"]'))
7.6、直接子標簽查找
1. t_list = bs.select("head > title") 2. print(t_list)
7.7、兄弟節點標簽查找
1. t_list = bs.select(".mnav ~ .bri") 2. print(t_list)
7.8、獲取內容
1. t_list = bs.select("title") 2. print(bs.select('title')[0].get_text())