Python爬虫教程-24-数据提取-BeautifulSoup4(二)
本篇介绍 bs 如何遍历一个文档对象
遍历文档对象
- contents:tag 的子节点以列表的方式输出
- children:子节点以迭代器形式返回
- descendants:所有子孙节点
- string:用string打印出标签的具体内容,不带有标签,只有内容
- 案例代码27bs3.py文件:https://xpwi.github.io/py/py%E7%88%AC%E8%99%AB/py27bs3.py
# BeautifulSoup 的使用案例# 遍历文档对象from urllib import requestfrom bs4 import BeautifulSoupurl = 'http://www.baidu.com/'rsp = request.urlopen(url)content = rsp.read()soup = BeautifulSoup(content, 'lxml')# bs 自动解码content = soup.prettify()print("=="*12)# 使用 contentsfor node in soup.head.contents: if node.name == "meta": print(node) if node.name == "title": print(node.string)print("=="*12)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
运行结果
常用string打印出标签的具体内容,不带有标签,只有内容
当然,如果觉得遍历太耗费资源,没有必要遍历的时候,可以使用搜索
搜索文档对象
- find_all(name, attrs, recursive, text, ** kwargs)
- 使用find_all(),返回的列表格式,也就是说如果 find_all(name=’meta’) ,如果有多个 meta 就以列表形式返回
- name 参数:按照哪个字符搜索,可以传入的内容为
- 1.字符串
- 2.正则表达式,使用正则需要编译:
例如:我们需要打印所有以 me 开头的标签内容
tags = soup.find_all(re.compile(‘^me’)) - 3.也可以是列表
- keyword 参数,可以用来表示属性
- text:对应 tag 的文本值
- 案例代码27bs4.py文件:https://xpwi.github.io/py/py%E7%88%AC%E8%99%AB/py27bs4.py
# BeautifulSoup 的使用案例# 搜索文档对象from urllib import requestfrom bs4 import BeautifulSoupimport reurl = 'http://www.baidu.com/'rsp = request.urlopen(url)content = rsp.read()soup = BeautifulSoup(content, 'lxml')# bs 自动解码content = soup.prettify()# 使用 find_all# 使用 name 参数print("=="*12)tags = soup.find_all(name='link')for i in tags: print(i)# 使用正则表达式print("=="*12)# 同时使用两个条件tags = soup.find_all(re.compile('^me'), content='always')# 这里直接打印 tags 会打印一个列表for i in tags: print(i)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
运行结果
因为使用两个条件,所以只匹配到一条 meta
下一篇介绍,BeautifulSoup 的 css 选择器
更多文章链接:Python 爬虫随笔
- 本笔记不允许任何个人和组织转载