BeautifulSoup官网学习笔记

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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值