Python使用Beautiful?Soup(BS4)庫(kù)解析HTML和XML
一、Beautiful Soup概述:
Beautiful Soup支持從HTML或XML文件中提取數(shù)據(jù)的Python庫(kù);
它支持Python標(biāo)準(zhǔn)庫(kù)中的HTML解析器,還支持一些第三方的解析器lxml。
Beautiful Soup自動(dòng)將輸入文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為utf-8編碼。
安裝:
pip install beautifulsoup4
可選擇安裝解析器
pip install lxmlpip install html5lib
二、BeautifulSoup4簡(jiǎn)單使用
假設(shè)有這樣一個(gè)Html,具體內(nèi)容如下:
<!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 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" rel="external nofollow" name="tj_trnews">新聞 </a>
<a class="mnav" rel="external nofollow" name="tj_trhao123">hao123 </a>
<a class="mnav" rel="external nofollow" name="tj_trmap">地圖 </a>
<a class="mnav" rel="external nofollow" name="tj_trvideo">視頻 </a>
<a class="mnav" rel="external nofollow" rel="external nofollow" name="tj_trtieba">貼吧 </a>
<a class="bri" rel="external nofollow" name="tj_briicon" style="display: block;">更多產(chǎn)品 </a>
</div>
</div>
</div>
</div>
</body>
</html>創(chuàng)建beautifulsoup4對(duì)象:
from bs4 import BeautifulSoup
file = open('./aa.html', 'rb')
html = file.read()
bs = BeautifulSoup(html, "html.parser") # 縮進(jìn)格式
print(bs.prettify()) # 格式化html結(jié)構(gòu)
print(bs.title) #
print(bs.title.name) # 獲取title標(biāo)簽的名稱 :title
print(bs.title.string) # 獲取title標(biāo)簽的文本內(nèi)容 : 百度一下,你就知道
print(bs.head) # 獲取head標(biāo)簽的所有內(nèi)容 :
print(bs.div) # 獲取第一個(gè)div標(biāo)簽中的所有內(nèi)容 :
print(bs.div["id"]) # 獲取第一個(gè)div標(biāo)簽的id的值 : wrapper
print(bs.a) # 獲取第一個(gè)a標(biāo)簽中的所有內(nèi)容 : <a rel="external nofollow" target="_blank">新聞 </a>
print(bs.find_all("a")) # 獲取所有的a標(biāo)簽中的所有內(nèi)容 : [....]
print(bs.find(id="u1")) # 獲取id="u1"的所有內(nèi)容 :
for item in bs.find_all("a"): # 獲取所有的a標(biāo)簽,并遍歷打印a標(biāo)簽中的href的值 :
print(item.get("href"))
for item in bs.find_all("a"): # 獲取所有的a標(biāo)簽,并遍歷打印a標(biāo)簽的文本值:
print(item.get_text())三、BeautifulSoup4四大對(duì)象種類
BeautifulSoup4將復(fù)雜HTML文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹形結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都是Python對(duì)象,所有對(duì)象可以歸納為4種:Tag 、NavigableString 、BeautifulSoup 、Comment、
1、Tag:標(biāo)簽
Tag通俗點(diǎn)講就是HTML中的一個(gè)個(gè)標(biāo)簽,例如:
print(bs.title) # 獲取title標(biāo)簽的所有內(nèi)容 print(bs.head) # 獲取head標(biāo)簽的所有內(nèi)容 print(bs.a) # 獲取第一個(gè)a標(biāo)簽的所有內(nèi)容 print(type(bs.a))# 類型
我們可以利用 soup 加標(biāo)簽名輕松地獲取這些標(biāo)簽的內(nèi)容,這些對(duì)象的類型是bs4.element.Tag。但是注意,它查找的是在所有內(nèi)容中的第一個(gè)符合要求的標(biāo)簽。
對(duì)于 Tag,它有兩個(gè)重要的屬性,是 name 和 attrs:
print(bs.name) # [document] #bs 對(duì)象本身比較特殊,它的 name 即為 [document]
print(bs.head.name) # head #對(duì)于其他內(nèi)部標(biāo)簽,輸出的值便為標(biāo)簽本身的名稱
print(bs.a.attrs) # 在這里,我們把 a 標(biāo)簽的所有屬性打印輸出了出來,得到的類型是一個(gè)字典。
print(bs.a['class']) ##還可以利用get方法,傳入屬性的名稱,二者是等價(jià)的,等價(jià) bs.a.get('class')
bs.a['class'] = "newClass"# 可以對(duì)這些屬性和內(nèi)容等等進(jìn)行修改
print(bs.a)
del bs.a['class'] # 還可以對(duì)這個(gè)屬性進(jìn)行刪除
print(bs.a)2、NavigableString:標(biāo)簽內(nèi)部的文字
既然我們已經(jīng)得到了標(biāo)簽的內(nèi)容,那么問題來了,我們要想獲取標(biāo)簽內(nèi)部的文字怎么辦呢?很簡(jiǎn)單,用 .string 即可,例如:
print(bs.title.string) # 百度一下,你就知道 print(type(bs.title.string)) #
3、BeautifulSoup:文檔的內(nèi)容
BeautifulSoup對(duì)象表示的是一個(gè)文檔的內(nèi)容。大部分時(shí)候,可以把它當(dāng)作 Tag 對(duì)象,是一個(gè)特殊的 Tag,我們可以分別獲取它的類型,名稱,以及屬性,例如:
print(type(bs.name)) #
print(bs.name) # [document]
print(bs.attrs) # {}4、Comment:注釋
Comment 對(duì)象是一個(gè)特殊類型的 NavigableString 對(duì)象,其輸出的內(nèi)容不包括注釋符號(hào)。
print(bs.a) # 此時(shí)不能出現(xiàn)空格和換行符,a標(biāo)簽如下: # print(bs.a.string) # 新聞 print(type(bs.a.string)) #
四、遍歷文檔樹所用屬性
- .contents:獲取Tag的所有子節(jié)點(diǎn),返回一個(gè)list
print(bs.head.contents) # tag的.contents屬性可以將tag的子節(jié)點(diǎn)以列表的方式輸出:[...] print(bs.head.contents[1]) # 用列表索引來獲取它的某一個(gè)元素:
- .children:獲取Tag的所有子節(jié)點(diǎn),返回一個(gè)生成器
for child in bs.body.children:
print(child)- .descendants:獲取Tag的所有子孫節(jié)點(diǎn)
- .parent:獲取Tag的父節(jié)點(diǎn)
- .parents:遞歸得到父輩元素的所有節(jié)點(diǎn),返回一個(gè)生成器
- .previous_sibling:獲取當(dāng)前Tag的上一個(gè)節(jié)點(diǎn),屬性通常是字符串或空白,真實(shí)結(jié)果是當(dāng)前標(biāo)簽與上一個(gè)標(biāo)簽之間的頓號(hào)和換行符
- .next_sibling:獲取當(dāng)前Tag的下一個(gè)節(jié)點(diǎn),屬性通常是字符串或空白,真是結(jié)果是當(dāng)前標(biāo)簽與下一個(gè)標(biāo)簽之間的頓號(hào)與換行符
- .previous_siblings:獲取當(dāng)前Tag的上面所有的兄弟節(jié)點(diǎn),返回一個(gè)生成器
- .next_siblings:獲取當(dāng)前Tag的下面所有的兄弟節(jié)點(diǎn),返回一個(gè)生成器
- .previous_element:獲取解析過程中上一個(gè)被解析的對(duì)象(字符串或tag),可能與previous_sibling相同,但通常是不一樣的
- .next_element:獲取解析過程中下一個(gè)被解析的對(duì)象(字符串或tag),可能與next_sibling相同,但通常是不一樣的
- .previous_elements:返回一個(gè)生成器,可以向前訪問文檔的解析內(nèi)容
- .next_elements:返回一個(gè)生成器,可以向后訪問文檔的解析內(nèi)容
- .strings:如果Tag包含多個(gè)字符串,即在子孫節(jié)點(diǎn)中有內(nèi)容,可以用此獲取,而后進(jìn)行遍歷
- .stripped_strings:與strings用法一致,只不過可以去除掉那些多余的空白內(nèi)容
- .has_attr:判斷Tag是否包含屬性
五、搜索文檔樹
1、find_all():過濾器
find_all(name, attrs, recursive, text, **kwargs):
find_all過濾器可以被用在tag的name中,節(jié)點(diǎn)的屬性等。
(1)name參數(shù):
字符串過濾:會(huì)查找與字符串完全匹配的內(nèi)容
a_list = bs.find_all("a")
print(a_list)正則表達(dá)式過濾:如果傳入的是正則表達(dá)式,那么BeautifulSoup4會(huì)通過search()來匹配內(nèi)容
import re
t_list = bs.find_all(re.compile("a"))
for item in t_list:
print(item)列表:如果傳入一個(gè)列表,BeautifulSoup4將會(huì)與列表中的任一元素匹配到的節(jié)點(diǎn)返回
t_list = bs.find_all(["meta","link"])
for item in t_list:
print(item)方法:傳入一個(gè)方法,根據(jù)方法來匹配
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)(2)kwargs參數(shù):
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中屬于關(guān)鍵字,所以加_以示區(qū)別)
for item in t_list:
print(item)(3)attrs參數(shù):
并不是所有的屬性都可以使用上面這種方式進(jìn)行搜索,比如HTML的data-*屬性:
t_list = bs.find_all(data-foo="value")
如果執(zhí)行這段代碼,將會(huì)報(bào)錯(cuò)。我們可以使用attrs參數(shù),定義一個(gè)字典來搜索包含特殊屬性的tag:
t_list = bs.find_all(attrs={"data-foo":"value"})
for item in t_list:
print(item)(4)text參數(shù):
通過text參數(shù)可以搜索文檔中的字符串內(nèi)容,與name參數(shù)的可選值一樣,text參數(shù)接受 字符串,正則表達(dá)式,列表
t_list = bs.find_all(text="hao123")
t_list = bs.find_all(text=["hao123", "地圖", "貼吧"])
t_list = bs.find_all(text=re.compile("\d"))當(dāng)我們搜索text中的一些特殊屬性時(shí),同樣也可以傳入一個(gè)方法來達(dá)到我們的目的:
def length_is_two(text):
return text and len(text) == 2
t_list = bs.find_all(text=length_is_two)(5)limit參數(shù):
可以傳入一個(gè)limit參數(shù)來限制返回的數(shù)量,當(dāng)搜索出的數(shù)據(jù)量為5,而設(shè)置了limit=2時(shí),此時(shí)只會(huì)返回前2個(gè)數(shù)據(jù)
t_list = bs.find_all("a",limit=2)find_all除了上面一些常規(guī)的寫法,還可以對(duì)其進(jìn)行一些簡(jiǎn)寫:
# 下面兩者是相等的
t_list = bs.find_all("a")
t_list = bs("a")
# 下面兩者是相等的
t_list = bs.a.find_all(text="新聞")
t_list = bs.a(text="新聞")2、find()
find()將返回符合條件的第一個(gè)Tag,有時(shí)我們只需要或一個(gè)Tag時(shí),我們就可以用到find()方法了。當(dāng)然了,也可以使用find_all()方法,傳入一個(gè)limit=1,然后再取出第一個(gè)值也是可以的,不過未免繁瑣。
t_list = bs.find_all("title",limit=1) # 返回只有一個(gè)結(jié)果的列表
t = bs.find("title") # 返回唯一值
t = bs.find("abc") # 如果沒有找到,則返回None從結(jié)果可以看出find_all,盡管傳入了limit=1,但是返回值仍然為一個(gè)列表,當(dāng)我們只需要取一個(gè)值時(shí),遠(yuǎn)不如find方法方便。但是如果未搜索到值時(shí),將返回一個(gè)None。
在上面介紹BeautifulSoup4的時(shí)候,我們知道可以通過bs.div來獲取第一個(gè)div標(biāo)簽,如果我們需要獲取第一個(gè)div下的第一個(gè)div,我們可以這樣:
t = bs.div.div
# 等價(jià)于
t = bs.find("div").find("div")六、CSS選擇器:select()方法
BeautifulSoup支持部分的CSS選擇器,在Tag獲取BeautifulSoup對(duì)象的.select()方法中傳入字符串參數(shù),即可使用CSS選擇器的語法找到Tag:
print(bs.select('title')) # 1、通過標(biāo)簽名查找
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[ rel="external nofollow" rel="external nofollow" ]'))
print(bs.select("head > title")) # 6、直接子標(biāo)簽查找
print(bs.select(".mnav ~ .bri")) # 7、兄弟節(jié)點(diǎn)標(biāo)簽查找
print(bs.select('title')[0].get_text()) # 8、獲取內(nèi)容七、綜合實(shí)例:
from bs4 import BeautifulSoup
import requests,re
req_obj = requests.get('https://www.baidu.com')
soup = BeautifulSoup(req_obj.text,'lxml')
'''標(biāo)簽查找'''
print(soup.title) #只是查找出第一個(gè)
print(soup.find('title')) #效果和上面一樣
print(soup.find_all('div')) #查出所有的div標(biāo)簽
'''獲取標(biāo)簽里的屬性'''
tag = soup.div
print(tag['class']) #多屬性的話,會(huì)返回一個(gè)列表
print(tag['id']) #查找標(biāo)簽的id屬性
print(tag.attrs) #查找標(biāo)簽所有的屬性,返回一個(gè)字典(屬性名:屬性值)
'''標(biāo)簽包的字符串'''
tag = soup.title
print(tag.string) #獲取標(biāo)簽里的字符串
tag.string.replace_with("哈哈") #字符串不能直接編輯,可以替換
'''子節(jié)點(diǎn)的操作'''
tag = soup.head
print(tag.title) #獲取head標(biāo)簽后再獲取它包含的子標(biāo)簽
'''contents 和 .children'''
tag = soup.body
print(tag.contents) #將標(biāo)簽的子節(jié)點(diǎn)以列表返回
print([child for child in tag.children]) #輸出和上面一樣
'''descendants'''
tag = soup.body
[print(child_tag) for child_tag in tag.descendants] #獲取所有子節(jié)點(diǎn)和子子節(jié)點(diǎn)
'''strings和.stripped_strings'''
tag = soup.body
[print(str) for str in tag.strings] #輸出所有所有文本內(nèi)容
[print(str) for str in tag.stripped_strings] #輸出所有所有文本內(nèi)容,去除空格或空行
'''.parent和.parents'''
tag = soup.title
print(tag.parent) #輸出便簽的父標(biāo)簽
[print(parent) for parent in tag.parents] #輸出所有的父標(biāo)簽
'''.next_siblings 和 .previous_siblings
查出所有的兄弟節(jié)點(diǎn)
'''
'''.next_element 和 .previous_element
下一個(gè)兄弟節(jié)點(diǎn)
'''
'''find_all的keyword 參數(shù)'''
soup.find_all(id='link2') #查找所有包含 id 屬性的標(biāo)簽
soup.find_all(href=re.compile("elsie")) #href 參數(shù),Beautiful Soup會(huì)搜索每個(gè)標(biāo)簽的href屬性:
soup.find_all(id=True) #找出所有的有id屬性的標(biāo)簽
soup.find_all(href=re.compile("elsie"), id='link1') #也可以組合查找
soup.find_all(attrs={"屬性名": "屬性值"}) #也可以通過字典的方式查找八、BeautifulSoup 和lxml(Xpath)對(duì)比
# 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 標(biāo)記
# 找到div_h2 標(biāo)記
h2 = mulu.find('h2')
if h2 != None:
h2_title = h2.string # 獲取標(biāo)題
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) 匹配括號(hào)內(nèi)的表達(dá)式,也表示一個(gè)組
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':h2_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 標(biāo)記
# 找到所有的 div_h2 標(biāo)記
div_h2 = div_mulu.xpath('./div[@class="mulu-title"]/center/h2/text()')
if len(div_h2) > 0:
h2_title = div_h2[0] # 獲取標(biāo)題
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) 匹配括號(hào)內(nèi)的表達(dá)式,也表示一個(gè)組
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':h2_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()到此這篇關(guān)于Python使用Beautiful Soup(BS4)庫(kù)解析HTML和XML的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python數(shù)據(jù)結(jié)構(gòu)鏈表操作從基礎(chǔ)到高級(jí)實(shí)例深究
鏈表是一種基礎(chǔ)的數(shù)據(jù)結(jié)構(gòu),它由一系列節(jié)點(diǎn)組成,每個(gè)節(jié)點(diǎn)都包含數(shù)據(jù)和指向下一個(gè)節(jié)點(diǎn)的引用,在Python中,可以使用類來實(shí)現(xiàn)鏈表,本文將介紹如何實(shí)現(xiàn)鏈表,并提供一些豐富的示例代碼來幫助你更好地理解其原理和應(yīng)用2023-12-12
Pycharm關(guān)于遠(yuǎn)程JupyterLab以及JupyterHub登錄問題
這篇文章主要介紹了Pycharm關(guān)于遠(yuǎn)程JupyterLab以及JupyterHub登錄問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06

