潮办公
  • python基础
  • python爬虫
  • vba
潮办公
一个教你高效办公的网站
  1. 首页
  2. python
  3. 正文

Day29:BeautifulSoup使用

2020年09月15日 27点热度 0人点赞 0条评论

官方文档如下介绍:

Beautiful Soup 是一个可以从 HTML 或 XML 文件中提取数据的 Python 库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup 会帮你节省数小时甚至数天的工作时间.

1. 安装

可以直接使用 pip 安装:

$ pip install beautifulsoup4

BeautifulSoup 不仅支持 HTML 解析器,还支持一些第三方的解析器,如,lxml,XML,html5lib 但是需要安装相应的库。

$ pip install lxml
$ pip install html5lib

2. Beautiful Soup的简单使用

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p>
<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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>
"""

# 从bs4中导入BeautifulSoup
from bs4 import BeautifulSoup

# 调用BeautifulSoup实例化得到一个soup对象
# 参数一: 解析文本
# 参数二:
# 参数二: 解析器(html.parser、lxml...)
soup = BeautifulSoup(html_doc, 'lxml')

print(soup)
print('*' * 100)
print(type(soup))
print('*' * 100)
# 文档美化
html = soup.prettify()
print(html)

3. Beautiful Soup之遍历文档树

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>37</b></p>
<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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
soup = BeautifulSoup(html_doc, 'lxml')

'''
遍历文档树:
    1、直接使用
    2、获取标签的名称
    3、获取标签的属性
    4、获取标签的内容
    5、嵌套选择
    6、子节点、子孙节点
    7、父节点、祖先节点
    8、兄弟节点
'''

# 1、直接使用
print(soup.p)  # 查找第一个p标签
print(soup.a)  # 查找第一个a标签

# 2、获取标签的名称
print(soup.head.name)  # 获取head标签的名称

# 3、获取标签的属性
print(soup.a.attrs)  # 获取a标签中的所有属性
print(soup.a.attrs['href'])  # 获取a标签中的href属性

# 4、获取标签的内容
print(soup.p.text)  #37

# 5、嵌套选择
print(soup.html.head)

# 6、子节点、子孙节点
print(soup.body.children)  # body所有子节点,返回的是迭代器对象
print(list(soup.body.children))  # 强转成列表类型

print(soup.body.descendants)  # 子孙节点
print(list(soup.body.descendants))  # 子孙节点

#  7、父节点、祖先节点
print(soup.p.parent)  # 获取p标签的父亲节点
# 返回的是生成器对象
print(soup.p.parents)  # 获取p标签所有的祖先节点
print(list(soup.p.parents))

# 8、兄弟节点
# 找下一个兄弟
print(soup.p.next_sibling)
# 找下面所有的兄弟,返回的是生成器
print(soup.p.next_siblings)
print(list(soup.p.next_siblings))

# 找上一个兄弟
print(soup.a.previous_sibling)  # 找到第一个a标签的上一个兄弟节点
# 找到a标签上面的所有兄弟节点
print(soup.a.previous_siblings)  # 返回的是生成器
print(list(soup.a.previous_siblings))

4.Beautiful Soup之搜索文档树

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>37</b></p>
<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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>
"""
'''
搜索文档树:
    find()  找一个
    find_all()  找多个

标签查找与属性查找:
    标签:
            name 属性匹配
            attrs 属性查找匹配
            text 文本匹配

        - 字符串过滤器
            字符串全局匹配

        - 正则过滤器
            re模块匹配

        - 列表过滤器
            列表内的数据匹配

        - bool过滤器
            True匹配

        - 方法过滤器
            用于一些要的属性以及不需要的属性查找。

    属性:
        - class_
        - id
'''

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'lxml')

# # 字符串过滤器
# name
p_tag = soup.find(name='p')
print(p_tag)  # 根据文本p查找某个标签
# # 找到所有标签名为p的节点
tag_s1 = soup.find_all(name='p')
print(tag_s1)
#
#
# # attrs
# # 查找第一个class为sister的节点
p = soup.find(attrs={"class": "sister"})
# print(p)
# # 查找所有class为sister的节点
tag_s2 = soup.find_all(attrs={"class": "sister"})
print(tag_s2)


# text
text = soup.find(text="37")
print(text)
#
#
# # 配合使用:
# # 找到一个id为link2、文本为Lacie的a标签
a_tag = soup.find(name="a", attrs={"id": "link2"}, text="Lacie")
print(a_tag)



# # 正则过滤器
import re
# name
p_tag = soup.find(name=re.compile('p'))
print(p_tag)

# 列表过滤器
import re
# name
tags = soup.find_all(name=['p', 'a', re.compile('html')])
print(tags)

# - bool过滤器
# True匹配
# 找到有id的p标签
p = soup.find(name='p', attrs={"id": True})
print(p)

# 方法过滤器
# 匹配标签名为a、属性有id没有class的标签
def have_id_class(tag):
    if tag.name == 'a' and tag.has_attr('id') and tag.has_attr('class'):
        return tag

tag = soup.find(name=have_id_class)
print(tag)
本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可
标签: python爬虫
最后更新:2020年09月15日

Tlntin

保持饥渴的专注,追求最佳的品质

点赞
< 上一篇

文章评论

取消回复
分类目录
最新 热点 随机
最新 热点 随机
Ubuntu20.04使用Premium15破解版教程 Linux使用OpenVpn教程 Ubuntu20.04安装最新微信2.9.5与Tim3.1.0 day10: 再谈range对象 day9: 了解Excel结构(下) day8: 了解Excel基本结构(中)
day9: 了解Excel结构(下) day5: vba编程基础(上) Linux使用OpenVpn教程 day20:面向对象编程(下) day18:os模块 day27:python正则表达式
标签聚合
Linux Ubuntu python爬虫 python基础 vba
其他信息
公众号
qq群

COPYRIGHT © 2020 潮办公. ALL RIGHTS RESERVED.

THEME KRATOS MADE BY VTROIS

粤ICP备18110825号-2