BeautifulSoup的介绍及简单用法
1. 介绍
beautiful是一种用来解析html或xml文件并根据需要提取相关内容的python库,一般用来做数据挖掘(爬取数据,并解析数据)
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')#,输入str,返回BeautifulSoup对象
#Beautiful Soup将复杂str转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment .
type(soup)
#bs4.BeautifulSoup
print(soup.prettify())#使用prettify方法将字符串解析成为标准缩进html格式内容输出,输出结果还是string
type(soup.prettify())
结果:html标签是按树结构存储的
<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 class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link3">
Tillie
</a>
;
and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
2.一些soup对象的小操作
soup.title#返回第一个title,包括他自身(标签(name),内容(string)以及它所有的子节点(标签,内容)
#<title>The Dormouse's story</title>
soup.title.name#第一个title节点的标签名字
#'title'
soup.title.string#第一个title节点的内容
#"The Dormouse's story"
#返回一个节点,是返回这个节点及其包含的所有子节点
soup.title.parent#第一个title节点的父节点(返回一个节点,是返回这个节点及其包含的所有子节点)
#<head><title>The Dormouse's story</title></head>
soup.title.parent.name#第一个title节点的父节点的标签名字
#'head'
soup.title.parent.string
#"The Dormouse's story"
soup.p
#<p class="title"><b>The Dormouse's story</b></p>
soup.p['class']#第一个p节点的class属性值
#['title']
soup.a
#<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
#为a的节点
soup.find_all('a')#返回所有标签为a的节点,返回节点的列表
#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.find(id="link3")
#<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
print(soup.get_text())#从文档中获取文字内容(除去标签,单纯返回所有内容)
#The Dormouse's story
#The Dormouse's story
#Once upon a time there were three little sisters; and their names were
#Elsie,
#Lacie and
#Tillie;
#and they lived at the bottom of a well.
#...
3.节点内部的理解
节点属性:类似于字典类型:标签属性为键,属性值为值d[key],d.get(key)
节点标签:link.name
节点内容:link.string
soup.a
#<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
soup.a.attrs#返回属性字典
#{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
for link in soup.find_all('a'):
print(link['href'])#print(link.get('href'))
print(link.name)
print(link.string)
#http://example.com/elsie
#a
#Elsie
#http://example.com/lacie
#a
#Lacie
#http://example.com/tillie
#a
#Tillie