Python 爬虫学习04 bs库示例学习(beautifulSoup)

示例请点击蓝字下载这里html文件进行配套学习

'''
BeaturifulSoup4 将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有
对象可以归纳为4种:

- Tag
- NavigableString
- BeautifulSoup
- Comment

'''

from bs4 import BeautifulSoup

file = open("./Mytest3.html","rb")
html = file.read()
#这个对象需要指定一个html.paser的解析器 已通过文档在解析器中形成一颗树
bs = BeautifulSoup(html,"html.parser")

#1.Tag 标签及其内容,拿到他所找到的第一个内容
# print(type(bs.head))
# print(bs.title)
# print(bs.a)
# print(bs.a.string)
# print(type(bs.a.string))

#2.NavigableString 标签里的内容(字符串)
# print(type(bs.a.attrs))

#3.BeautifulSoup 表示整个文档
#print(bs)

#4.Comment 是一个特殊的NavigableString

#文档的遍历
# print(bs.body.contents)
# print(bs.body.contents[1])

import re
#文档的搜索
#(1)find_all()
#字符串过滤:会查找与字符串完全匹配的内容
# t_list = bs.find_all(re.compile("a"))
# print(t_list)

#方法 : 传入一个函数(方法),根据函数的要求来搜索
# 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)kwargs 参数
# t_list = bs.find_all(type="text")
#
# for item in t_list:
#     print(item)

#3.text参数
#t_list = bs.find_all(value="ouou1")

#也可以写成列表的形式
#t_list = bs.find_all(value=["ouou1","ouou2"])

#应用正则表达式来查找包含特定文本的内容(标签里的字符串)
# t_list = bs.find_all(value=re.compile("\d"))
# for item in t_list:
#     print(item)

#4.limit 参数
# t_list = bs.find_all("a")
# #limit 限定获取个数
# t_list = bs.find_all("a",limit=2)
#
# for item in t_list:
#     print(item)

#css选择器
#通过标签来查找
#t_list = bs.select('button')

#通过.类名来查找
#t_list = bs.select('.droptarget')

#通过#id来查找
#t_list = bs.select("#myVideo")

#通过属性来查找
#t_list = bs.select('input[type="color"]')

#通过子标签来查找
# t_list = bs.select('body > p')
# for item in t_list:
#     print(item)

猜你喜欢

转载自blog.csdn.net/weixin_44291381/article/details/114534629