爬虫15-bs4

Beautiful Soup 是一个 HTML/XML 的解析器,主要用于解析和提取 HTML/XML 数据。 它基于 HTML DOM 的,会载入整个文档,解析整个 DOM 树,因此时间和内存开销都会 大很多,所以性能要低于 lxml。

BeautifulSoup 用来解析 HTML 比较简单,API 非常人性化,支持 CSS 选择器、Python 标准库中的 HTML 解析器,也支持 lxml 的 XML 解析器。

可以通过pip install beautifulsoup4安装beautifulsoup

beautifulsoup基础的使用,这里只介绍常见的使用案例

from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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>
"""
soup = BeautifulSoup(html, 'lxml')

1、find_all(name, attrs, recursive, text, **kwargs)

import re
# 传字符串 查找所有的b标签
print(soup.find_all('b'))
# 查找所有的a标签
print(soup.find_all('a'))
# 传正则表达式 查找所有以b开头的标签 如b、body
for tag in soup.find_all(re.compile("^b")):
    # 输出标签的名字
    print(tag.name)
    # 输出标签的文本
    print(tag.text)
    # 输出标签的内容 包括换行符
    print(tag.contents)
# 传列表 查找所有的a和b标签
print(soup.find_all(["a", "b"]))

# 传入keyword 查找id为link2的标签
print(soup.find_all(id='link2'))

# 传入文本内容
print(soup.find_all(text="Elsie"))
print(soup.find_all(text=["Tillie", "Elsie", "Lacie"]))
print(soup.find_all(text=re.compile("Dormouse")))

2、css选择器 select

# 通过标签名查找
print(soup.select('title'))
print(soup.select('a'))
print(soup.select('b'))
# 通过class查找
print(soup.select('.sister'))
# 通过id查找
print(soup.select('#link1'))
# 组合查找
print(soup.select('p #link1'))
# 子标签查找
print(soup.select("head > title"))
# 通过属性查找
print(soup.select('p a[href="http://example.com/elsie"]'))
# 获取内容 和.text类似
print(soup.select('title')[0].get_text())

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值