from bs4 import BeautifulSoup
f = open("./htmlDemo1.html","rb")
html = f.read().decode("utf-8")
bs = BeautifulSoup(html,"html.parser")
#print(bs.title)
# print(bs.head)
# print(bs.h1)
#print(type(bs.h1))
#1. Tag 标签及其内容 (只能拿到它所找到的第一个内容)
#print(bs.title.string)
#print(type(bs.title.string))
#2. NavigableString 标签里的内容(字符串)
# print(bs.a.attrs)
# print(bs.p.attrs) #获取标签的属性,并放在字典中
#print(type(bs))
#3. BeautifulSoup 表示整个文档
# print(bs.name)
# print(bs.attrs)
# print(bs)
# print(bs.p.string)
# print(type(bs.p.string))
#4. Comment 是一个特殊的NavigableString,输出的内容不包含注释符号
#文档的遍历
# print(bs.head.contents)
# print(bs.head.contents[1])
#文档的搜索
#1. find_all()
#(1)字符串过滤:会查找与字符串完全匹配的内容
# t_list = bs.find_all("a")
# print(t_list)
#(2)正则表达式搜索:使用search内容来匹配搜索
# import re
# t_list = bs.find_all(re.compile("a"))
# print(t_list)
#(3)方法:传入一个函数(方法),根据函数的要求来查询
# def name_is_exists(Tag):
# return Tag.has_attr("name")
#
# t_list = bs.find_all(name_is_exists)
# # print(t_list)
# for item in t_list:
# print(t_list)
#2. kwargs 参数
# t_list = bs.find_all(class_="hot")
# t_list = bs.find_all(href = "http://baidu.com")
# print(t_list)
#3. text参数
# t_list = bs.find_all(text = "hehehe")
# t_list = bs.find_all(text=["hehehe","苹果"])
# for item in t_list:
# print(item)
#4. limit参数
# t_list = bs.find_all("p",limit=3)
# print(t_list)
#css选择器
# t_list = bs.select("title") #通过标签来查找
# t_list = bs.select("head > title") #通过子标签来查找
t_list = bs.select(".hot ~ .cool")
print(t_list[0].get_text()) #通过兄弟标签来查找
# t_list = bs.select(".hot") #通过类名来查找
# t_list = bs.select("#title1") #通过id来查找
# t_list = bs.select("a[href='http://baidu.com']") #通过属性来查找
for item in t_list:
print(item)