beautifulsoup4 练习

from bs4 import BeautifulSoup
# 自定义网页进行过滤
html = """
<html>
    <title>this is a test website</title>
    <body>
        <p id='fruit' class='myfavourite'>i like eating apple</p>
        <p id='fruit'>i like eating peach too</p>
        <p id='website'>i have my personal website </p>
        <p id='country'>i am chinese</p>
        <p> id='session 'i like summer</p>
        <h1 class="favourite runnning">i like playing football</h1>
        <td>
            <tr>i am a boy</tr>
            <tr>i am 17 years old</tr>
        </td>
    <body>
</html>
"""
# 建立beautifulsoup4 对象,设定解析器为 lxml
bs = BeautifulSoup(html,"lxml")
# 将 html 格式化后以Unicode编码输出,每个XML/HTML标签都独占一行。
print(bs.prettify())
print("我是分隔符===============================================")
# 打印第一个 tag 为 title 的标签
print(bs.title)
# 打印第一个 tag 为 title 的标签名字
print(bs.title.name)
# 打印第一个 p 标签的属性
print(bs.p.attrs)
# 打印第一个 p 标签 id 属性的值
print(bs.p.attrs['id'])
# 打印第一个 tag 为 title 中的文字
print(bs.title.string)
# 打印第一个 tag 为 title 的 父标签的 名字
print(bs.title.parent.name)
# 在bs4 中最大的标签是 [document],在html 上面的是[document] 标签
print(bs.html.parent.name)
# 打印第一个匹配到 attrs={xxx} 的标签
print(bs.find(attrs={'id':'fruit',"class":"myfavourite"}))
# 搜索所有匹配的标签,返回一个列表
print(bs.find_all(id='fruit'))

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值