BeautifulSoup模块使用

1.安装BeautifulSoup模块

pip install beautifulsoup4

2.文件中引入

from bs4 import BeautifulSoup

3.使用BeautifulSoup

with open('./tests/python.html',encoding='utf-8') as f:
    texts = f.read()

bs = BeautifulSoup(texts,'html.parser')
print(bs.title)
# 获取节点文本
print(bs.title.text)
# 获取节点名称
print(bs.title.name)
# 取父节点名称
print(bs.title.parent.name)
# 取出所有的子节点
print(bs.p.children)


print(list(bs.p.children))
# 获取节点的属性
print(bs.p['class'])
# 取出所有指定节点
print(bs.find_all('a'))

links = bs.find_all('a')
for link in links:
    print(link['href'])

print(bs.find('a'))

# 按条件查找对象
# 查找p标签中class为titile的标签 因为class是python的关键字,所以要加个下划线class_  find返回时对象
print(bs.find('p',class_ = 'title'))

print(bs.find('p',id = 'title1'))

# 查找所有class为title的标签 find_all 返回时列表
print(bs.find_all(class_='title'))

# 取得文档内的所有文本内容
print(bs.get_text())

# 工整地打印整个代码
print(bs.prettify())

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值