BeautifulSoup的基本用法

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。
它是一个灵活又方便的网页解析库,处理高效,支持多种解析器。
利用它就不用编写正则表达式也能方便的实现网页信息的抓取。
通常人们把 beautifulSoup 叫作“美味的汤,绿色的浓汤”,简称:美丽(味)汤
它的官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html (中)
https://www.crummy.com/software/BeautifulSoup/bs4/doc/ (英)
安装
快速安装
pip install beautifulsoup4 或 easy_install BeautifulSoup4
解析库
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。
 
复制代码
# -*- coding:utf-8 -*-

from bs4 import BeautifulSoup

html = """
<html><head><title>haha,The Dormouse's story</tittle></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')
print(soup)    # 输出解析的html对象
print(soup.prettify())      # 格式化
print(soup.title)             # 输出标题<title>,eg: <title>haha,The Dormouse's story</title>
print(soup.title.string)      # 输出title标题的内容字符串
print(soup.title.parent.name) # 输出<title>节点父节点的名字

print(soup.find_all('a')) # 输出所有标签<a>组成的list
print(soup.find(id='link3')) # 返回包含id='link3'的标签所有内容
复制代码

 

posted @   宇宙刘  阅读(796)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示