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()) #输出文档中全部文本内容(除去标签)