這篇文章主要介紹了Python如何使用Beautiful Soup(BS4)庫解析HTML和XML的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Python如何使用Beautiful Soup(BS4)庫解析HTML和XML文章都會有所收獲,下面我們一起來看看吧。
Beautiful Soup支持從HTML或XML文件中提取數據的Python庫;
它支持Python標準庫中的HTML解析器,還支持一些第三方的解析器lxml。
Beautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼。
pip install beautifulsoup4
可選擇安裝解析器
pip install lxml
pip install html5lib
假設有這樣一個Html,具體內容如下:
<!DOCTYPE html> <html> <head> <meta content="text/html;charset=utf-8" http-equiv="content-type" /> <meta content="IE=Edge" http-equiv="X-UA-Compatible" /> <meta content="always" name="referrer" /> <link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css" rel="external nofollow" rel="stylesheet" type="text/css" /> <title>百度一下,你就知道 </title> </head> <body link="#0000cc"> <div id="wrapper"> <div id="head"> <div class="head_wrapper"> <div id="u1"> <a class="mnav" href="http://news.baidu.com" rel="external nofollow" name="tj_trnews">新聞 </a> <a class="mnav" href="https://www.hao123.com" rel="external nofollow" name="tj_trhao123">hao123 </a> <a class="mnav" href="http://map.baidu.com" rel="external nofollow" name="tj_trmap">地圖 </a> <a class="mnav" href="http://v.baidu.com" rel="external nofollow" name="tj_trvideo">視頻 </a> <a class="mnav" href="http://tieba.baidu.com" rel="external nofollow" rel="external nofollow" name="tj_trtieba">貼吧 </a> <a class="bri" href="//www.baidu.com/more/" rel="external nofollow" name="tj_briicon" >更多產品 </a> </div> </div> </div> </div> </body> </html>
創建beautifulsoup4對象:
from bs4 import BeautifulSoup
file = open('./aa.html', 'rb')
html = file.read()
bs = BeautifulSoup(html, "html.parser") # 縮進格式
print(bs.prettify()) # 格式化html結構
print(bs.title) #
print(bs.title.name) # 獲取title標簽的名稱 :title
print(bs.title.string) # 獲取title標簽的文本內容 : 百度一下,你就知道
print(bs.head) # 獲取head標簽的所有內容 :
print(bs.div) # 獲取第一個div標簽中的所有內容 :
print(bs.div["id"]) # 獲取第一個div標簽的id的值 : wrapper
print(bs.a) # 獲取第一個a標簽中的所有內容 : <a href="http://news.baidu.com/" rel="external nofollow" target="_blank">新聞 </a>
print(bs.find_all("a")) # 獲取所有的a標簽中的所有內容 : [....]
print(bs.find(id="u1")) # 獲取id="u1"的所有內容 :
for item in bs.find_all("a"): # 獲取所有的a標簽,并遍歷打印a標簽中的href的值 :
print(item.get("href"))
for item in bs.find_all("a"): # 獲取所有的a標簽,并遍歷打印a標簽的文本值:
print(item.get_text())BeautifulSoup4將復雜HTML文檔轉換成一個復雜的樹形結構,每個節點都是Python對象,所有對象可以歸納為4種:Tag 、NavigableString 、BeautifulSoup 、Comment、
Tag通俗點講就是HTML中的一個個標簽,例如:
print(bs.title) # 獲取title標簽的所有內容 print(bs.head) # 獲取head標簽的所有內容 print(bs.a) # 獲取第一個a標簽的所有內容 print(type(bs.a))# 類型
我們可以利用 soup 加標簽名輕松地獲取這些標簽的內容,這些對象的類型是bs4.element.Tag。但是注意,它查找的是在所有內容中的第一個符合要求的標簽。
對于 Tag,它有兩個重要的屬性,是 name 和 attrs:
print(bs.name) # [document] #bs 對象本身比較特殊,它的 name 即為 [document]
print(bs.head.name) # head #對于其他內部標簽,輸出的值便為標簽本身的名稱
print(bs.a.attrs) # 在這里,我們把 a 標簽的所有屬性打印輸出了出來,得到的類型是一個字典。
print(bs.a['class']) ##還可以利用get方法,傳入屬性的名稱,二者是等價的,等價 bs.a.get('class')
bs.a['class'] = "newClass"# 可以對這些屬性和內容等等進行修改
print(bs.a)
del bs.a['class'] # 還可以對這個屬性進行刪除
print(bs.a)既然我們已經得到了標簽的內容,那么問題來了,我們要想獲取標簽內部的文字怎么辦呢?很簡單,用 .string 即可,例如:
print(bs.title.string) # 百度一下,你就知道 print(type(bs.title.string)) #
BeautifulSoup對象表示的是一個文檔的內容。大部分時候,可以把它當作 Tag 對象,是一個特殊的 Tag,我們可以分別獲取它的類型,名稱,以及屬性,例如:
print(type(bs.name)) #
print(bs.name) # [document]
print(bs.attrs) # {}Comment 對象是一個特殊類型的 NavigableString 對象,其輸出的內容不包括注釋符號。
print(bs.a) # 此時不能出現空格和換行符,a標簽如下: # print(bs.a.string) # 新聞 print(type(bs.a.string)) #
.contents:獲取Tag的所有子節點,返回一個list
print(bs.head.contents) # tag的.contents屬性可以將tag的子節點以列表的方式輸出:[...] print(bs.head.contents[1]) # 用列表索引來獲取它的某一個元素:
.children:獲取Tag的所有子節點,返回一個生成器
for child in bs.body.children: print(child)
.descendants:獲取Tag的所有子孫節點
.parent:獲取Tag的父節點
.parents:遞歸得到父輩元素的所有節點,返回一個生成器
.previous_sibling:獲取當前Tag的上一個節點,屬性通常是字符串或空白,真實結果是當前標簽與上一個標簽之間的頓號和換行符
.next_sibling:獲取當前Tag的下一個節點,屬性通常是字符串或空白,真是結果是當前標簽與下一個標簽之間的頓號與換行符
.previous_siblings:獲取當前Tag的上面所有的兄弟節點,返回一個生成器
.next_siblings:獲取當前Tag的下面所有的兄弟節點,返回一個生成器
.previous_element:獲取解析過程中上一個被解析的對象(字符串或tag),可能與previous_sibling相同,但通常是不一樣的
.next_element:獲取解析過程中下一個被解析的對象(字符串或tag),可能與next_sibling相同,但通常是不一樣的
.previous_elements:返回一個生成器,可以向前訪問文檔的解析內容
.next_elements:返回一個生成器,可以向后訪問文檔的解析內容
.strings:如果Tag包含多個字符串,即在子孫節點中有內容,可以用此獲取,而后進行遍歷
.stripped_strings:與strings用法一致,只不過可以去除掉那些多余的空白內容
.has_attr:判斷Tag是否包含屬性
find_all(name, attrs, recursive, text, **kwargs):
find_all過濾器可以被用在tag的name中,節點的屬性等。
字符串過濾:會查找與字符串完全匹配的內容
a_list = bs.find_all("a")
print(a_list)正則表達式過濾:如果傳入的是正則表達式,那么BeautifulSoup4會通過search()來匹配內容
import re
t_list = bs.find_all(re.compile("a"))
for item in t_list:
print(item)列表:如果傳入一個列表,BeautifulSoup4將會與列表中的任一元素匹配到的節點返回
t_list = bs.find_all(["meta","link"]) for item in t_list: print(item)
方法:傳入一個方法,根據方法來匹配
def name_is_exists(tag):
return tag.has_attr("name")
t_list = bs.find_all(name_is_exists)
for item in t_list:
print(item)t_list = bs.find_all(id="head") # 查詢id=head的Tag t_list = bs.find_all(href=re.compile(http://news.baidu.com)) # 查詢href屬性包含ss1.bdstatic.com的Tag t_list = bs.find_all(class_=True) # 查詢所有包含class的Tag(注意:class在Python中屬于關鍵字,所以加_以示區別) for item in t_list: print(item)
并不是所有的屬性都可以使用上面這種方式進行搜索,比如HTML的data-*屬性:
t_list = bs.find_all(data-foo="value")
如果執行這段代碼,將會報錯。我們可以使用attrs參數,定義一個字典來搜索包含特殊屬性的tag:
t_list = bs.find_all(attrs={"data-foo":"value"})
for item in t_list:
print(item)通過text參數可以搜索文檔中的字符串內容,與name參數的可選值一樣,text參數接受 字符串,正則表達式,列表
t_list = bs.find_all(text="hao123")
t_list = bs.find_all(text=["hao123", "地圖", "貼吧"])
t_list = bs.find_all(text=re.compile("\d"))當我們搜索text中的一些特殊屬性時,同樣也可以傳入一個方法來達到我們的目的:
def length_is_two(text): return text and len(text) == 2 t_list = bs.find_all(text=length_is_two)
可以傳入一個limit參數來限制返回的數量,當搜索出的數據量為5,而設置了limit=2時,此時只會返回前2個數據
t_list = bs.find_all("a",limit=2)find_all除了上面一些常規的寫法,還可以對其進行一些簡寫:
# 下面兩者是相等的
t_list = bs.find_all("a")
t_list = bs("a")
# 下面兩者是相等的
t_list = bs.a.find_all(text="新聞")
t_list = bs.a(text="新聞")find()將返回符合條件的第一個Tag,有時我們只需要或一個Tag時,我們就可以用到find()方法了。當然了,也可以使用find_all()方法,傳入一個limit=1,然后再取出第一個值也是可以的,不過未免繁瑣。
t_list = bs.find_all("title",limit=1) # 返回只有一個結果的列表
t = bs.find("title") # 返回唯一值
t = bs.find("abc") # 如果沒有找到,則返回None從結果可以看出find_all,盡管傳入了limit=1,但是返回值仍然為一個列表,當我們只需要取一個值時,遠不如find方法方便。但是如果未搜索到值時,將返回一個None。
在上面介紹BeautifulSoup4的時候,我們知道可以通過bs.div來獲取第一個div標簽,如果我們需要獲取第一個div下的第一個div,我們可以這樣:
t = bs.div.div
# 等價于
t = bs.find("div").find("div")BeautifulSoup支持部分的CSS選擇器,在Tag獲取BeautifulSoup對象的.select()方法中傳入字符串參數,即可使用CSS選擇器的語法找到Tag:
print(bs.select('title')) # 1、通過標簽名查找
print(bs.select('a'))
print(bs.select('.mnav')) # 2、通過類名查找
print(bs.select('#u1')) # 3、通過id查找
print(bs.select('div .bri')) # 4、組合查找
print(bs.select('a[class="bri"]')) # 5、屬性查找
print(bs.select('a[href="http://tieba.baidu.com" rel="external nofollow" rel="external nofollow" ]'))
print(bs.select("head > title")) # 6、直接子標簽查找
print(bs.select(".mnav ~ .bri")) # 7、兄弟節點標簽查找
print(bs.select('title')[0].get_text()) # 8、獲取內容from bs4 import BeautifulSoup
import requests,re
req_obj = requests.get('https://www.baidu.com')
soup = BeautifulSoup(req_obj.text,'lxml')
'''標簽查找'''
print(soup.title) #只是查找出第一個
print(soup.find('title')) #效果和上面一樣
print(soup.find_all('div')) #查出所有的div標簽
'''獲取標簽里的屬性'''
tag = soup.div
print(tag['class']) #多屬性的話,會返回一個列表
print(tag['id']) #查找標簽的id屬性
print(tag.attrs) #查找標簽所有的屬性,返回一個字典(屬性名:屬性值)
'''標簽包的字符串'''
tag = soup.title
print(tag.string) #獲取標簽里的字符串
tag.string.replace_with("哈哈") #字符串不能直接編輯,可以替換
'''子節點的操作'''
tag = soup.head
print(tag.title) #獲取head標簽后再獲取它包含的子標簽
'''contents 和 .children'''
tag = soup.body
print(tag.contents) #將標簽的子節點以列表返回
print([child for child in tag.children]) #輸出和上面一樣
'''descendants'''
tag = soup.body
[print(child_tag) for child_tag in tag.descendants] #獲取所有子節點和子子節點
'''strings和.stripped_strings'''
tag = soup.body
[print(str) for str in tag.strings] #輸出所有所有文本內容
[print(str) for str in tag.stripped_strings] #輸出所有所有文本內容,去除空格或空行
'''.parent和.parents'''
tag = soup.title
print(tag.parent) #輸出便簽的父標簽
[print(parent) for parent in tag.parents] #輸出所有的父標簽
'''.next_siblings 和 .previous_siblings
查出所有的兄弟節點
'''
'''.next_element 和 .previous_element
下一個兄弟節點
'''
'''find_all的keyword 參數'''
soup.find_all(id='link2') #查找所有包含 id 屬性的標簽
soup.find_all(href=re.compile("elsie")) #href 參數,Beautiful Soup會搜索每個標簽的href屬性:
soup.find_all(id=True) #找出所有的有id屬性的標簽
soup.find_all(href=re.compile("elsie"), id='link1') #也可以組合查找
soup.find_all(attrs={"屬性名": "屬性值"}) #也可以通過字典的方式查找# test.py
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup, SoupStrainer
import traceback
import json
from lxml import etree
import re
import time
def getHtmlText(url):
try:
r = requests.get(url, headers=headers)
r.raise_for_status()
if r.encoding == 'ISO-8859-1':
r.encoding = r.apparent_encoding
return r.text
except:
traceback.print_exc()
# ----------使用BeautifulSoup解析------------------------
def parseWithBeautifulSoup(html_text):
soup = BeautifulSoup(html_text, 'lxml')
content = []
for mulu in soup.find_all(class_='mulu'): # 先找到所有的 div class=mulu 標記
# 找到div_h3 標記
h3 = mulu.find('h3')
if h3 != None:
h3_title = h3.string # 獲取標題
lst = []
for a in mulu.select('div.box a'):
href = a.get('href') # 找到 href 屬性
box_title = a.get('title') # 找到 title 屬性
pattern = re.compile(r'\s*\[(.*)\]\s+(.*)') # (re) 匹配括號內的表達式,也表示一個組
match = pattern.search(box_title)
if match != None:
date = match.group(1)
real_title = match.group(2)
lst.append({'href':href,'title':real_title,'date':date})
content.append({'title':h3_title,'content':lst})
with open('dmbj_bs.json', 'w') as fp:
json.dump(content, fp=fp, indent=4)
# ----------使用Xpath解析------------------------
def parseWithXpath(html_text):
html = etree.HTML(html_text)
content = []
for div_mulu in html.xpath('.//*[@class="mulu"]'): # 先找到所有的 div class=mulu 標記
# 找到所有的 div_h3 標記
div_h3 = div_mulu.xpath('./div[@class="mulu-title"]/center/h3/text()')
if len(div_h3) > 0:
h3_title = div_h3[0] # 獲取標題
a_s = div_mulu.xpath('./div[@class="box"]/ul/li/a')
lst = []
for a in a_s:
href = a.xpath('./@href')[0] # 找到 href 屬性
box_title = a.xpath('./@title')[0] # 找到 title 屬性
pattern = re.compile(r'\s*\[(.*)\]\s+(.*)') # (re) 匹配括號內的表達式,也表示一個組
match = pattern.search(box_title)
if match != None:
date = match.group(1)
real_title = match.group(2)
lst.append({'href':href,'title':real_title,'date':date})
content.append({'title':h3_title,'content':lst})
with open('dmbj_xp.json', 'w') as fp:
json.dump(content, fp=fp, indent=4)
def main():
html_text = getHtmlText('http://www.seputu.com')
print(len(html_text))
start = time.clock()
parseWithBeautifulSoup(html_text)
print('BSoup cost:', time.clock()-start)
start = time.clock()
parseWithXpath(html_text)
print('Xpath cost:', time.clock()-start)
if __name__ == '__main__':
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'
headers={'User-Agent': user_agent}
main()關于“Python如何使用Beautiful Soup(BS4)庫解析HTML和XML”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Python如何使用Beautiful Soup(BS4)庫解析HTML和XML”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。