Beautiful soup 使用方法
Introduction
- Beautiful Soup 是一個能從html或xml文件中,提取數據的python庫
- 目前主流的版本是bs4,bs3已經不再支持
本文以在 html 中查找元素爲例,所測試的數據如下:
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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/elsie" class="sister" id="link1">Elsie</a>,
<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>
<p class="story">...</p>
"""
初始化
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,"lxml")
單個標籤操作方法(也適用與多標籤遍歷情況)
'''輸出標籤的基本信息'''
print(soup.title) # 輸出title標籤,和它所包含的內容
print(soup.title.name) # 輸出title標籤名稱,就是 title
print(soup.title.string) # 輸出標籤title所包含的內容
print(soup.title.parent.name) # 輸出title父標籤的名稱
print(soup.a.get('id')) # 獲得標籤屬性值
運行結果
<title>The Dormouse's story</title>
title
The Dormouse's story
head
link1
說明:
- 直接使用 soup.tag_name 默認只輸出匹配到的第一個結果;
將重複的標籤全部找出—僅根據標籤名
all_tags = soup.find_all('a') # 使用find_all可以輸入全部要查找的標籤
for tag in all_tags:
print("tag = "+str(tag)+"\t tag.string = "+tag.string+"\t tag.name = "+str(tag.name)+"\n" )
運行結果:
tag = <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> tag.string = Elsie tag.name = a
tag = <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> tag.string = Lacie tag.name = a
tag = <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> tag.string = Tillie tag.name = a
說明:
- find_all 函數,會查找全部匹配標籤。
- 用在單個標籤上的處理方法都可以在遍歷多標籤時使用;
- 多標籤匹配返回的結果數據類型是:bs4.element.ResultSet
將重複的標籤全部找出—根據標籤名+屬性共同確定
# 舉一個和本例子不相關的代碼, 以後再補充這個例子
tas =soup.find_all('a',{'class':'tag-val'})
根據屬性值匹配標籤
'''根據標籤屬性匹配'''
ret = soup.find(id="link1")
print(ret)
print(ret.string)
print(ret.name)
運行結果
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
Elsie
a
說明:
- 根據屬性值匹配標籤,只輸出第一個匹配成個的標籤;
- 根據屬性值匹配的標籤,得到的結果是bs4.element.Tag 所以它不可以遍歷;
匹配指定標籤,並輸出指定的屬性值
例如,輸入全部 標籤a 的href 屬性值
for link in soup.find_all("a"):
print(link.get('href'))
運行結果
http://example.com/elsie
http://example.com/lacie
http://example.com/tillie
對整個文檔操作
print(soup.prettify()) # 按照標準的縮緊格式的結果輸出
print(soup.get_text()) #輸出文檔中全部文本內容(除去標籤)