爬虫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())

猜你喜欢

转载自blog.csdn.net/qwerLoL123456/article/details/83544452
今日推荐