Python爬虫-BeautifulSoup
Tag
标签及其内容:拿到它所找到的第一个内容
bs.title
bs.a
bs.head
NavigableString
标签里面的内容(字符串)
bs.title.string
bs.a.string
bs.head.string
如何获得标签的属性值?
bs.a.attrs
BeautifulSoup
表示整个文档
Comment
是一个特殊的NavigableString,输出的内容不包含注释符号
bs.a.string
文档的遍历
contents
获取Tag的所有子节点,返回一个list
bs.head.contents[1]
children
获取Tag的所有子节点,返回一个生成器
for child in bs.body.children:
print(child)
文档的搜索
find_all()
字符串过滤:会查找与字符串完全匹配的内容
t_list=bs.find_all("a")
print(t_list)
正则表达式搜索
使用search()方法来匹配
## 标签里面含有a的都找出来
t_list=bs.find_all(re.compile("a))
函数方式搜索()
传入一个函数,根据函数的要求来搜索
def name_is_exists(tag):
return tag.has_attr("name")
t_list=bs.find_all(name_is_exists)
kwargs-参数
t_list=bs.find_all(id='head')
t_list=bs.find_all(class_=True)
text 参数
t_list=bs.find_all(text="hao123")
limit 参数
t_list=bs.find_all("a",limit=3)
css选择器
t_list=bs.select("title")## 标签查找
t_list=bs.select(".mnav")## 类名查找
t_list=bs.select("#u1") ## id查找
t_list=bs.select("a[class='bri']") ##属性查找
t_lisy=bs.select("head">"title") ##
t_list=bs.select(".mnav ~ .bri")