Python爬虫利器:BeautifulSoup库
来源:互联网 发布:百度人工智能世界第一 编辑:程序博客网 时间:2024/06/06 20:28
Beautiful Soup parses anything you give it, and does the tree traversal stuff for you.
BeautifulSoup库是解析、遍历、维护 “标签树” 的功能库(遍历,是指沿着某条搜索路线,依次对树中每个结点均做一次且仅做一次访问)。https://www.crummy.com/software/BeautifulSoup
BeautifulSoup库我们常称之为bs4,导入该库为:from bs4 import BeautifulSoup。其中,import BeautifulSoup即主要用bs4中的BeautifulSoup类。
bs4库解析器
BeautifulSoup类的基本元素
import requestsfrom bs4 import BeautifulSoupres = requests.get('http://www.pmcaff.com/site/selection')soup = BeautifulSoup(res.text,'lxml')print(soup.a)# 任何存在于HTML语法中的标签都可以用soup.<tag>访问获得,当HTML文档中存在多个相同<tag>对应内容时,soup.<tag>返回第一个。print(soup.a.name)# 每个<tag>都有自己的名字,可以通过<tag>.name获取,字符串类型print(soup.a.attrs)print(soup.a.attrs['class'])# 一个<tag>可能有一个或多个属性,是字典类型print(soup.a.string)# <tag>.string可以取到标签内非属性字符串soup1 = BeautifulSoup('<p><!--这里是注释--></p>','lxml')print(soup1.p.string)print(type(soup1.p.string))# comment是一种特殊类型,也可以通过<tag>.string取到
运行结果:
<a class="no-login" href="">登录</a>
a
{'href': '', 'class': ['no-login']} ['no-login']
登录
这里是注释
<class 'bs4.element.Comment'>
bs4库的HTML内容遍历
HTML的基本结构
标签树的下行遍历
# 遍历所有先辈节点时,包括soup本身,所以要if...else...判断for parent in soup.a.parents: if parent is None: print(parent) else: print(parent.name)运行结果:
div
div
body
html
[document]
标签树的平行遍历
# 遍历后续节点for sibling in soup.a.next_sibling: print(sibling)# 遍历前续节点for sibling in soup.a.previous_sibling: print(sibling)bs4库的prettify()方法
prettify()方法可以将代码格式搞的标准一些,用soup.prettify()表示。在PyCharm中,用print(soup.prettify())来输出。
操作环境:Mac,Python 3.6,PyCharm 2016.2
参考资料:中国大学MOOC课程《Python网络爬虫与信息提取》
----- End -----
更多精彩内容关注我公众号:杜王丹
作者:杜王丹,互联网产品经理- Python爬虫利器:BeautifulSoup库
- python爬虫之BeautifulSoup库
- Python 网页爬虫-BeautifulSoup库的学习
- Python爬虫入门(三)BeautifulSoup库
- Python爬虫库学习笔记-BeautifulSoup
- Python网络爬虫之BeautifulSoup库
- python 爬虫之 BeautifulSoup 库详解
- python爬虫之BeautifulSoup
- python爬虫之-BeautifulSoup
- python beautifulsoup 爬虫学习
- python爬虫之BeautifulSoup
- python-爬虫-beautifulsoup
- python爬虫爬取斗图网BeautifulSoup
- python爬虫--BeautifulSoup
- python爬虫(BeautifulSoup)
- python爬虫利器-request库
- [爬虫] Python爬虫 urllib BeautifulSoup
- python 自己写爬虫 ----- BeautifulSoup
- RCNN用到的SelectiveSearch的理解笔记
- 记录
- okHttp的简单封装使用
- 加密软件的未来发展方向 自动备份功能应该成为一种标准
- ZKFailoverController( zkfc)介绍
- Python爬虫利器:BeautifulSoup库
- php中多维数组排序
- JS为什么有时候要做两次encodeURI
- JDK8-时间API(十)
- 挑战程序竞赛系列(15):2.6快速幂运算
- 使用neo4j shell命令行工具时遭遇“connection refused” error的解决方法(草稿版)
- MongoDB--架构搭建(主从、副本集)之主从
- join连接表时是先join还是先where
- Codeforces 760B Frodo and pillows