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
bsobj = BeautifulSoup(html_doc,'html.parser') #转化成bs对象,html格式,BeautifulSoup有检验html格式,若有缺失标签,会自动补齐
bsobj = BeautifulSoup(html_doc,'xml')#xml格式
print(bsobj.prettify())
from bs4 import BeautifulSoup
soup_html = BeautifulSoup(open('C:/Users/Administrator/Desktop/hello.html').read(),'html.parser')#参数可以是一个文件句柄
soup_html
#bsobj.标签名
bsobj.title
bsobj.title.name
bsobj.p#获取第一个P标签
bsobj.p['class']#p标签的class属性值
bsobj.a
#结合find_all和find方法使用
bsobj.find_all('a')#获取所有的a标签,以列表形式返回
bsobj.find('a')#获取第一个a标签
bsobj.find(id='link2')
bsobj.find_all('a')[0].get('href')#获取第一个a标签的href属性值
bsobj.find('a').get('href')#获取第一个a标签的href属性值
bsobj.a.get_text()#获取第一个a标签的内容
#对象种类
#Tag
type(bsobj.title)#bs4.element.Tag
#Tag的名称
bsobj.title.name#'title'
#bsobj.title.name='Title'#修改标签的名称
#Tag Attributes
bsobj.find('a').attrs#获取a标签的属性,以字典形式返回
bsobj.a.attrs
bsobj.a['href']#获取a标签href属性值
bsobj.a['class']
bsobj.a['id']='link22'#修改a标签的id属性值
del bsobj.a['id']#删除a标签的id属性
bsobj.a['id']='link1'#a标签添加id属性
bsobj.a
#多值属性
#html支持多值属性
obj =BeautifulSoup('<p class="aaa bbb"></p>','html.parser')
obj.p['class']#返回['aaa', 'bbb']
#xml不支持多值属性
obj =BeautifulSoup('<p class="aaa bbb"></p>','xml')
obj.p['class']#返回'aaa bbb'
#获取标签的内容
bsobj.a.string
bsobj.a.get_text()
type(bsobj.a.string)#bs4.element.NavigableString(可遍历字符串)
type(bsobj.a.get_text())#str
bsobj.a.string='Elsie'#修改a标签的内容
bsobj.a.string.replace_with('eee')#替换a标签的内容
bsobj.a.string
#BeautifulSoup对象表示的是一个文档的全部内容,可以理解为一个Tag对象,但其没有name和attribute属性,但有一个特殊的.name属性
bsobj.name#'[document]'
comment_str = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(comment_str)
comment = soup.b.string
type(comment)#bs4.element.Comment
#.contents 和.children:都指的是直接节点
print(bsobj.html.contents)
tag = bsobj.html.contents[1]
bsobj.html.contents[1].contents[1].contents
tag.c
BeautifulSoup官网学习笔记
最新推荐文章于 2023-05-12 11:24:04 发布