使用pip install beautifulsoup4
标签的基本元素
title![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094824294-892601506.png)
示例
示例
注意:同一父节点的儿子节点才构成平行遍历的关系
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094849310-1564082426.png)
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094852966-16092495.png)
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094855638-409407912.png)
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094856466-178880871.png)
结合形式解析和搜索方法,提取关键信息![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094858638-821570432.png)
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094903091-1222363459.png)
from bs4 import BeautifulSoup
import requests
r = requests.get("http://python123.io/ws/demo.html")
print r.text
print BeautifulSoup(r.text,'html.parser').prettify()
BeautifulSoup的基本元素
BS4库是解析,遍历,维护“标签树”的功能库
BeautifulSoup库 指代一个标签树
BeautifulSoup库对应于一个HTML或XML文档的全部内容
BS库的解析器
解析器 | 使用方法 | 条件 |
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 |
基本元素 | 说明 |
Tag | 标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾 |
Name | 标签的名字,<p>...</p>的名字的'p',格式:<tag>.name |
Attributes | 标签的属性,字典形式组织,格式<tag>.attrs |
NavigableString | 标签内非属性字符串,<>...</>中的字符串,格式:<tag>.string |
Comment | 标签内字符串的注释部分,一种特殊的Comment类型<!--comment--> |
soup.<tag>
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094824294-892601506.png)
BS库的HTML文档的遍历
标签树的下行遍历
属性 | 说明 |
.contents | 子节点的列表,将<tag>所有儿子节点存入列表 |
.children | 子节点的迭代类型,与.contents类似,用于循环遍历儿子的节点 |
.descendants | 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历 |
from bs4 import BeautifulSoup
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
s = BeautifulSoup(demo,'html.parser')
print s.prettify()
print s.body.contents
for child in s.body.children:
print(child)
for child in s.body.descendants:
print(child)
标签树的上午遍历
属性 | 说明 |
.parent | 节点的父亲标签 |
.parents | 节点先辈标签的迭代类型,用于循环遍历先辈节点 |
from bs4 import BeautifulSoup
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
s = BeautifulSoup(demo,'html.parser')
print s.prettify()
for parent in s.a.parents:
if parent is None:
print parent
else:
print parent.name
平行遍历
属性 | 说明 |
.next_sibiling | 返回按照HTML文本顺序的下一个平行节点的标签 |
.previous_sililing | 返回按照HTML文本顺序的止一个平行节点的标签 |
.next_sibilings | 迭代类型,返回按照HTML文本顺序的后续所有平行节点的标签 |
.previous_sibilings | 迭代类型,返回按照HTML文本顺序的前续所有平行节点的标签 |
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094843169-1599818524.png)
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094848341-15335842.png)
信息标记的三种形式
HTML语言可以将超文件内容(即声音,图片,视频等内容)嵌入到文本当中
XML扩展标记语言
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094849310-1564082426.png)
实例
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094850810-2070219264.png)
JSON JavaScript Object Notation
key:value键值对
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094852966-16092495.png)
实例
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094854763-1425664399.png)
YMAL
采用无类型的键值对来表示信息
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094855638-409407912.png)
实例
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094856466-178880871.png)
标记语言 | 特点 | 应用场景 |
XML | 最早的通用信息标记语言,可扩展性好,但繁琐 | Internet上的信息交互与传递 |
JSON | 信息有类型,适合程序处理(js),较XML简洁 | 移动应用云端和节点的信息通信,无注释 |
YAML | 信息无类型,文本信息比例较高,可读性较好 | 种类系统的配置文件,有注释易读 |
XML JSON YAML 搜索
需要标记解析器及文本查找函数
实例:解析一个文档中的所有链接信息
from bs4 import BeautifulSoup
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
s = BeautifulSoup(demo,'html.parser')
for link in s.find_all('a'):
print link.get('href')
<>.find_all(name,attrs,recursive,string,**kwargs)
name: 需要检索的标签的名字,可以是列表,是True的话将返回所有的标签
attrs: 要检索的标签的属性值 ,e.g. soup.find_all('p','course') soup.find_all(id='link1') soup.find_all(id = re.compile(u'link'))
recursive: 是否递归的检索子孙后代节点,默认是True
string: <>...</>中的字符串区域的检索字符串 soup.find_all(string = re.compile(u'python'))
<tag>(...)来代替<tag>.find_all(...)
soup.(...)来代替soup.find_all(...)
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094858638-821570432.png)
实例1:中国大学排名的定向爬虫
版本1
#CrawUnivRankingA.py
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def fillUnivList(ulist, html):
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string, tds[1].string, tds[3].string])
def printUnivList(ulist, num):
print("{:^10}\t{:^6}\t{:^10}".format("排名","学校名称","总分"))
for i in range(num):
u=ulist[i]
print("{:^10}\t{:^6}\t{:^10}".format(u[0],u[1],u[2]))
def main():
uinfo = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) # 20 univs
main()
输出
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094903091-1222363459.png)
版本2
#CrawUnivRankingB.py
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def fillUnivList(ulist, html):
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string, tds[1].string, tds[3].string])
def printUnivList(ulist, num):
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分",chr(12288)))
for i in range(num):
u=ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288)))
def main():
uinfo = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) # 20 univs
main()
输出
![](https://images2015.cnblogs.com/blog/1169492/201705/1169492-20170527094905138-1998778585.png)