非常感谢 https://b23.tv/wNSgXs教学分享,以下是学习笔记
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器html.parser
这里用到的baidu.tml文件是
<!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>
BS解析html
from bs4 import BeautifulSoup
file = open("./baidu.html","rb") #二进制读取
html = file.read().decode("utf-8")
bs = BeautifulSoup(html,"html.parser") #利用BS来解析文件
Tag
#1.Tag 标签及内容;只能拿到所找到的第一个内容 加入标签是:head /head 取到标签中的内容
print(bs.title)
对比 html 源码,可以看见得到的内容就是源码中第一个title的内容
NavigableString
print(bs.title.string) #一个标签的内容
print(bs.a.attrs) #一个标签的所有属性
BeautifulSoup
print(bs) # 整个文档
注释类型
print(bs.a.string)
print(type(bs.a.string)) #comment类型 是一个特殊的NavigableString,输出内容不包含注释符号
对比源码输出的是第一个a中的注释部分
标签内容提取
1. 文档的遍历
# 文档的遍历 所有都拿到
print(bs.head.contents) # bs.head.contents 可以获得到所有标签的内容 返回列表形式,通过序列号可以到具体的某个内容
# 列表中的第一个
print(bs.head.contents[1])
2.find_all()
2.1 常量搜索
# 字符串过滤,查找与字符串完全匹配的内容
t_list = bs.find_all("a")
print(t_list)
2.2 正则表达式搜索;使用search()方法来匹配搜索
import re
t_list = bs.find_all(re.compile("a"))
print(t_list)
2..3 方法:传入一个函数,根据函数要求来搜索
#只搜索有name属性的标签的内容
def name_is_exists(tag):
return tag.has_attr("name")
t_list = bs.find_all(name_is_exists)
for item in t_list:
print(item)
print(t_list)
2.4. kwargs 参数
t_list = bs.find_all(id = "head")
for item in t_list:
print(item)
t_list = bs.find_all(href="http://tieba.baidu.com")
for item in t_list:
print(item)