beautiful soup是python的一个网页解析库,处理快捷; 支持多种解析器,功能强大。教程细致讲解beautiful soup的深入使用、节点选择器、css选择器、beautiful soup4的方法选择器等重要知识点,是学好爬虫的基础课程。
学习目标
- 掌握节点选择器提取信息的方法
1. 提取信息的方法
通过选择元素的方式,我们获取到了标签的全部信息,如果我们想要提取标签中的信息,可以使用如下方式:
(1) 获取节点名称
-
格式:
soup.tag.name -
返回值:字符串
-
示例:
html = '''''' from bs4 import beautifulsoup soup = beautifulsoup(html, 'lxml') # 获取a标签的名字 result = soup.a.name print(result) # 输出结果: ahello
- foo
- bar
- ]ay
- foo
- bar
(2) 获取节点属性值
-
格式:
soup.tag.attrs -
返回值:字典
-
示例:
html = '''''' from bs4 import beautifulsoup soup = beautifulsoup(html, 'lxml') # 获取a标签的属性 result = soup.a.attrs print(result) # 输出结构 { 'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}hello
- foo
- bar
- ]ay
- foo
- bar
(3) 获取节点文本内容
-
格式:
soup.tag.string -
返回值:字符串
-
示例:
html = '''''' from bs4 import beautifulsoup soup = beautifulsoup(html, 'lxml') # 获取a标签的内容 result = soup.a.string print(result) # 输出结构 elsiehello
- foo
- bar
- ]ay
- foo
- bar
2. 总结
节点选择器提取信息的方法:
- soup.tag.name
- 用来提取节点名称
- soup.tag.attrs
- 用来提取属性
- soup.tag.string
- 用来提取内容