python 爬虫之Beautiful Soup 库
1. 介绍:
Beautiful Soup将复杂HTML文档转换成一个复杂 的树形结构,每个节点都是Python对象,
所有对象可以归纳为4种:
tag,
NavigableString,
BeautifulSoup,
Comment
2.分析网站
<!DOCTYPE html>
<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="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/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 id="u1">
<a class="mnav" href="http://news.baidu.com" name="tj_trnews"><!--新闻--></a>
<a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a>
<a class="mnav" href="https://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>
<a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">更多产品 </a>
</div>
</div>
</div>
</div>
</body>
</html>
调用库
from bs4 import BeautifulSoup
file = open("./baidu.html", 'rb')
# 'r':默认值,表示从文件读取数据。; 'b':表示要读写二进制数据
html = file.read().decode("utf-8")
bs = BeautifulSoup(html, "html.parser")
第一种:Tag 标签及其内容:拿到它所找到的第一个内容
print(bs.title)
print(bs.a)
print(bs.head)
print(type(bs.body))
第二种:NavigableString 标签里的内容(字符串)
print(bs.title.string)
# 标签里的属性
print(bs.a.attrs)
第三种:BeautifulSoup 表示整个文档
print(bs)
第四种:Comment 是一个特殊的NavigableString,输出的内容不包含注释符号
print(bs.a.string)
print(type(bs.a.string))
文档的遍历、搜素
# 遍历
print(bs.head.contents)
print(bs.head.contents[1])
# 文档的搜索(常用!)
(1) find_all()
# 字符串过滤:会查找与字符串完全匹配的内容
t_list = bs.find_all('a')
print(t_list)
# 1).正则表达式搜素:使用search()方法来匹配内容
# 标签里含有什么,就把标签全找出来
import re
t_list = bs.find_all(re.compile("a"))
print(t_list)
# 2)方法: 传入一个函数(方法),根据函数的要求来搜索
def name_is_exist(tag):
return tag.has_attr("name")
# 判断标签是否有响应属性返回值 False 或者 True
t_list = bs.find_all(name_is_exist)
for i in t_list:
print(t_list)
# (2) kwargs 参数
t_list = bs.find_all(id = "head")
t_list = bs.find_all(href="http://news.baidu.com" )
t_list = bs.find_all(class_ = True) # 含有class
for i in t_list:
print(t_list)
# (3). text参数
t_list = bs.find_all(text="hao123")
t_list = bs.find_all(text=["hao123","地图","贴吧"])
for i in t_list:
print(t_list)
t_list = bs.find_all(text=re.compile("\d"))
for i in t_list:
print(t_list)