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'的标签所有内容
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本