一:简介
1.BeautifulSoup 是一个可以从HTML或XML文件中提取数据的Python库,它的使用方式相对于正则来说更加的简单方便,常常能够节省我们大量的时间。
2.BeautifulSoup的安装也是非常方便的,pip安装即可。
pip install beautifulsoup4
3.解析器:
BeautifulSoup解析网页需要指定一个可用的解析器,以下是主要几种解析器:
由于这个解析的过程在大规模的爬取中是会影响到整个爬虫系统的速度的,所以推荐使用的是lxml,速度会快很多,而lxml需要单独安装:
pip install lxml
soup = BeautifulSoup(html_doc, 'lxml') # 指定解析器
提示:如果一段HTML或XML文档格式不正确的话,那么在不同的解析器中返回的结果可能是不一样的,所以要指定某一个解析器。
二.例子
公共代码
from bs4 import BeautifulSoup # 导包
html_str="""<!DOCTYPE html>
<html>
<head>
<title>爬虫</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://www.taobao.com">
<link rel="stylesheet" href="https://www.baidu.com">
<link rel="stylesheet" href="http://at.alicdn.com/t/font_684044_un7umbuwwfp.css">
</head>
<body>
<!-- footer start -->
<footer id="footer">
<div class="footer-box">
<div class="footer-content" >
<p class="top-content" id="111">
<a href="http://www.taobao.com">淘宝</a>
<span class="link">
<a class="product" href="https://www.baidu.com">关于Python</a>
<a href="http://www.taobao.com">好好学习</a>
<a href="javascript:void(0)">人生苦短</a>
<a href="javascript:void(0)">我用Python</a>
</span>
<span class="about-me">关于我: <i class="PyWhich py-wechat"></i> 忽略</span>
</p>
<p class="bottom-content">
<span>地址: xxxx</span>
<span>联系方式: <a href="tel:400-1567-315">400-1567-315</a> (24小时在线)</span>
</p>
</div>
<p class="copyright-desc">
Copyright © 爬虫有限公司. All Rights Reserved
</p>
</div>
</footer>
</body>
</html>
"""
第一部分:
soup=BeautifulSoup(html_str,'lxml') # html转换成操作对象
print(type(soup))
print(soup.a) # 1.获取第一个符合条件的标签
print(soup.a['href']) # 2.获取第一个符合条件的标签属性
print(soup.a.text) # 3.获取内容
# print(soup.body)
print('======================================================')
print(soup.body.children) # <list_iterator object at 0x00000271ADDB9C18>
# 4.亲戚标签选择
body=soup.body # 获取body标签
tags=body.children # 仅仅是儿子元素
# print(list(tags))
print('******************************************************')
for tag in tags:
print(tag)
print('--------------------------------------------------------')
运行截图:
D:\py学习01\venv\Scripts\python.exe D:/py学习01/python爬虫基础/网页解析-05/网页解析_bs4-01.py
<class 'bs4.BeautifulSoup'>
<a href="http://www.taobao.com">淘宝</a>
http://www.taobao.com
淘宝
======================================================
<list_iterator object at 0x00000150B7E5BBA8>
******************************************************
footer start
<footer id="footer">
<div class="footer-box">
<div class="footer-content">
<p class="top-content" id="111">
<a href="http://www.taobao.com">淘宝</a>
<span class="link">
<a class="product" href="https://www.baidu.com">关于Python</a>
<a href="http://www.taobao.com">好好学习</a>
<a href="javascript:void(0)">人生苦短</a>
<a href="javascript:void(0)">我用Python</a>
</span>
<span class="about-me">关于我: <i class="PyWhich py-wechat"></i> 忽略</span>
</p>
<p class="bottom-content">
<span>地址: xxxx</span>
<span>联系方式: <a href="tel:400-1567-315">400-1567-315</a> (24小时在线)</span>
</p>
</div>
<p class="copyright-desc">
Copyright © 爬虫有限公司. All Rights Reserved
</p>
</div>
</footer>
第二部分: