认识爬虫 —— bs4提取
安装:pip install bs4
导入:from bs4 import BeautifulSoup
创建 Beautiful Soup 对象:soup = BeautifulSoup(html, features="lxml")
其中html
为要解析的文档,features
为使用的解析器类型
BS4支持的解析器有html.parse(Python内置)、lxml、和html5lib等
注意:lxml只会局部遍历,而BeautifulSoup则会全文档搜索
搜索文档树:
find:与findall
函数一样用法,区别在于find
返回一个对象,如果没有则返回None
,而findall
返回列表。
findall:返回所有匹配的列表,否则返回空列表;
css选择器:使用select
方法,返回的是列表
选择器 | 描述 |
标签选择器 | soup.select('title') |
类选择器 | soup.select('.sister') |
id选择器 | soup.select('#title') |
层级选择器 | soup.select('p title') |
属性选择器 | soup.select('a[href="http://baidu.com"]') |
组合选择器 | soup.select('div.class1.class2') |
获取文本内容 get_text() | soup.select('title')[0].get_text() |
获取属性 get('属性名') | soup.select('title')[0].get('href') |