文章目录
前言
编写工具
pycharm
学习链接:
https://www.bilibili.com/video/BV12E411A7ZQ?p=18&spm_id_from=333.880.my_history.page.click
本文为学习笔记!!!!
提示:以下是本篇文章正文内容,下面案例可供参考
一、需要导入的模块
import bs4
from bs4 import BeautifulSoup
bs4和xlwt的导入教程:https://blog.csdn.net/qq_45834835/article/details/124612854
二、概念
1.BS4概念
将复杂的HTML文档转换成树形结构 每个节点都是python对象 所有对象归纳为4种:
1.Tag
2.NavigableString
3.BeautifulSoup
4.Comment
2.四种对象概念
# rb是读取⼆进制⽂件,⾮⼈⼯书写的数据如.jpeg等这些。
file = open('douban.html','rb')
html = file.read()
# bs对象指定一个解析器去分析文档 'html.parser'解析模式
bs = BeautifulSoup(html,'html.parser')
#1.Tag 标签及其内容 默认只能拿到第一个内容
# bs.标签 返回标签与标签里的内容
print(bs.title)
print(type(bs.a))
#2.NavigableString 标签里面的内容
# 得到标签里面的内容
print(bs.title.string)
print(type(bs.title.string))
# 拿到标签里面的属性 以键值对的形式返回
print(bs.a.attrs)
#3. BeautifulSoup 表示整个文档
print(type(bs))
print(bs)
#4.Comment 是特殊的NavigableString 输出内容不包括注释内容
三、文档的遍历与搜索
1.文档的遍历(还有很多,可以去开发文档找)
file = open('douban.html','rb')
html = file.read().decode('utf-8')
bs = BeautifulSoup(html,'html.parser')
# contents 获取Tag的所有子节点 返回一个生成器
print(bs.head.contents)
print(bs.head.contents[1])
2.文档的搜索
1. find_all + 正则表达式/自定义方法
file = open('douban.html','rb')
html = file.read().decode('utf-8')
bs = BeautifulSoup(html,'html.parser')
# find_all 查找所有 字符串过滤:会查找与字符串完全匹配的内容
#1.find_all+正则表达式搜索 使用search()方法来匹配内容
t_list = bs.find_all(re.compile('a'))
# 2.find_all+用方法搜索:传入一个函数 根据函数的要求搜索
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)
2.find_all + kwargs 参数
#通过ID查找
t_list = bs.find_all(id='anony-nav-banner')
#通过判断class存在查找
t_list = bs.find_all(class_ = True)
for item in t_list:
print(item)
3.find_all + text参数
t_list = bs.find_all(text = re.compile('\d')) #应用正则表达式来查找包含特定文本的内容(标签里的字符串)
for item in t_list:
print(item)
4.find_all + limit参数
#限制输出三次
t_list = bs.find_all('a',limit=3)
for item in t_list:
print(item)
5.css选择器 select
# 通过标签
t_list= bs.select('title')
# 通过类名
t_list = bs.select('.rec_topics_name')
# 通过ID
t_list = bs.select('#lnk-book')
# 通过属性
t_list = bs.select('a[class="lnk-book"]')
# 通过子标签
t_list = bs.select("head > title")
# 通过兄弟标签
t_list = bs.select('.mnav ~ .bri')
print(t_list[0].get_text())
for item in t_list:
print(item)