文章目录
Beautiful Soup库入门
一:Beautiful Soup库安装
1、管理员身份运行cmd 执行
pip install beautifulsoup4
2、安装测试
import requests
response = requests.get("http://www.baidu.com")
response.encoding = response.apparent_encoding
#print(response.text)
Demo = response.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(Demo,'html.parser')
print(soup.prettify())
运行结果: #看起来整洁一点
<!DOCTYPE html>
<!--STATUS OK-->
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="content-type"/>
<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="always" name="referrer"/>
<link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>
<title>
百度一下,你就知道
</title>
</head>
<body link="#0000cc">
<div id="wrapper">
<div id="head">
<div class="head_wrapper">
<div class="s_form">
<div class="s_form_wrapper">
<div id="lg">
<img height="129" hidefocus="true" src="//www.baidu.com/img/bd_logo1.png" width="270"/>
</div>
<form action="//www.baidu.com/s" class="fm" id="form" name="f">
<input name="bdorz_come" type="hidden" value="1"/>
<input name="ie" type="hidden" value="utf-8"/>
<input name="f" type="hidden" value="8"/>
<input name="rsv_bp" type="hidden" value="1"/>
<input name="rsv_idx" type="hidden" value="1"/>
<input name="tn" type="hidden" value="baidu"/>
<span class="bg s_ipt_wr">
<input autocomplete="off" autofocus="" class="s_ipt" id="kw" maxlength="255" name="wd" value=""/>
</span>
<span class="bg s_btn_wr">
<input class="bg s_btn" id="su" type="submit" value="百度一下"/>
</span>
</form>
</div>
</div>
<div id="u1">
<a class="mnav" href="http://news.baidu.com" name="tj_trnews">
新闻
</a>
<a class="mnav" href="http://www.hao123.com" name="tj_trhao123">
hao123
</a>
<a class="mnav" href="http://map.baidu.com" name="tj_trmap">
地图
</a>
<a class="mnav" href="http://v.baidu.com" name="tj_trvideo">
视频
</a>
<a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">
贴吧
</a>
<noscript>
<a class="lb" href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1" name="tj_login">
登录
</a>
</noscript>
<script>
document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
</script>
<a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">
更多产品
</a>
</div>
</div>
</div>
<div id="ftCon">
<div id="ftConw">
<p id="lh">
<a href="http://home.baidu.com">
关于百度
</a>
<a href="http://ir.baidu.com">
About Baidu
</a>
</p>
<p id="cp">
©2017 Baidu
<a href="http://www.baidu.com/duty/">
使用百度前必读
</a>
<a class="cp-feedback" href="http://jianyi.baidu.com/">
意见反馈
</a>
京ICP证030173号
<img src="//www.baidu.com/img/gs.gif"/>
</p>
</div>
</div>
</div>
</body>
</html>
3、对Beautiful Soup库的理解
Beautiful Soup库,也叫beautifulsoup4 或 bs4; 约定引用方式如下:
from bs4 import BeautifulSoup
import bs4
即主要是用BeautifulSoup 类。
BeautifulSoup对应一个HTML/XML文档的全部内容。
Beautiful Soup库是解析、遍历、维护“标签树”的功能库
<a>...</a>: 标签 Tag
<a href="http://home.baidu.com">关于百度</a>
其中:a是名称。,一般成对出现,href="http://home.baidu.com"
是属性Attributes,有零个或多个。
二、Beautiful Soup库的基本元素
1、Beautiful Soup库解析器
soup = BeautifulSoup('data','html.parser')
解析器 | 使用方法 | 条件 |
---|---|---|
bs4的HTML解析器 | BeautifulSoup(mk,‘html.parser’) | 安装bs4库 |
lxml的HTML解析器 | BeautifulSoup(mk,‘lxml’) | pip install lxml |
lxml的XML解析器 | BeautifulSoup(mk,‘xml’) | pip install lxml |
html5lib的解析器 | BeautifulSoup(mk,‘html5lib’) | pip install html5lib |
2、BeautifulSoup类的基本元素
<a href="http://home.baidu.com">关于百度</a>
基本元素 | 说明 |
---|---|
Tag | 标签,最基本的信息组织单元,分别用<> 和</>标明开头和结尾 |
Name | 标签的名字,<a>...</a> 的名字是‘a’,格式:.name |
Attributes | 标签的属性,字典形式组织,格式:.attrs |
NavigabString | 标签内非属性字符串,<>…</>中字符串,格式:.string |
Comment | 标签内字符串的注释部分,一种特殊的Comment类型 |
①、Tag标签
import requests
response = requests.get("http://www.baidu.com")
Demo = response.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(Demo,'html.parser')
print(soup.title)
print(soup.a)
运行结果:
<title>百度一下,你就知道</title>
<a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a>
任何存在于HTML语法中的标签都可以用soup.访问获得 当HTML文档中存在多个相同对应内容时,soup.会返回第一个。
②、Tag的name
import requests
response = requests.get("http://www.baidu.com")
Demo = response.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(Demo,'html.parser')
print(soup.a.name)
print(soup.a.parent.name)
print(soup.a.parent.parent.name)
运行结果:
a
div
div
每个都有自己的名字,通过.name获取,属于字符串类型。
③、Tag的attrs(属性)
import requests
response = requests.get("http://www.baidu.com")
Demo = response.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(Demo,'html.parser')
print(soup.a.attrs)
print(soup.a.attrs['name'])
print(type(soup.a.attrs))
print(type(soup.a))
运行结果:
{'href': 'http://news.baidu.com', 'name': 'tj_trnews', 'class': ['mnav']}
tj_trnews
<class 'dict'>
<class 'bs4.element.Tag'>
一个可以有 0或多个属性,属于字典类型。
④、Tag的NavigableString
import requests
response = requests.get("http://www.baidu.com")
Demo = response.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(Demo,'html.parser')
print(soup.a)
print(soup.a.string)
print(type(soup.a.string))
运行结果:
<a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a>
新闻
<class 'bs4.element.NavigableString'>
NavigableString可以跨越多个层次
⑤、Tag的Comment
from bs4 import BeautifulSoup
newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>", "html.parser")
print(newsoup.b.string)
print(type(newsoup.b.string))
print(newsoup.p.string)
print(type(newsoup.p.string))
运行结果:
This is a comment
<class 'bs4.element.Comment'>
This is not a comment
<class 'bs4.element.NavigableString'>
Comment是一种特殊类型
三、基于bs4库的HTML内容遍历方法
图片来源于嵩天老师
1、标签树的下行遍历
属性 | 说明 |
---|---|
.contents | 子节点的列表,将所有儿子节点存入列表 |
.children | 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点 |
.descendants | 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历 |
BeautifulSoup类型是标签树的根节点
for child in soup.body.children:
print(child) #遍历儿子节点
for child in soup.body.descendants:
print(child) #遍历子孙节点
2、标签树的上行遍历
属性 | 说明 |
---|---|
.parent | 节点的父亲标签 |
.parents | 节点先辈标签的迭代类型,用于循环遍历先辈节点 |
for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
遍历所有先辈节点,包括soup本身,所以要区别判断
3、标签树的平行遍历
属性 | 说明 |
---|---|
.next_sibling | 返回按照HTML文本顺序的下一个平行节点标签 |
.previous_sibling | 返回按照HTML文本顺序的上一个平行节点标签 |
.next_siblings | 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签 |
.previous_siblings | 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签 |
平行遍历发生在同一个父节点下的各节点间
for sibling in soup.a.next_sibling:
print(sibling) #遍历后续节点
for sibling in soup.a.previous_sibling:
print(sibling) #遍历前续节点