Python爬虫教程-24-数据提取-BeautifulSoup4(二)

Python爬虫教程-24-数据提取-BeautifulSoup4(二)

本篇介绍 bs 如何遍历一个文档对象

遍历文档对象

  • contents:tag 的子节点以列表的方式输出
  • children:子节点以迭代器形式返回
  • descendants:所有子孙节点
  • string:用string打印出标签的具体内容,不带有标签,只有内容
  • 案例代码27bs3.py文件:https://xpwi.github.io/py/py爬虫/py27bs3.py
# BeautifulSoup 的使用案例
# 遍历文档对象

from urllib import request
from bs4 import BeautifulSoup

url = 'http://www.baidu.com/'

rsp = request.urlopen(url)
content = rsp.read()

soup = BeautifulSoup(content, 'lxml')

# bs 自动解码
content = soup.prettify()

print("=="*12)
# 使用 contents
for node in soup.head.contents:
    if node.name == "meta":
        print(node)
    if node.name == "title":
        print(node.string)
print("=="*12)

运行结果

这里写图片描述
常用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爬虫/py27bs4.py
# BeautifulSoup 的使用案例
# 搜索文档对象

from urllib import request
from bs4 import BeautifulSoup
import re

url = '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)

运行结果:

这里写图片描述
因为使用两个条件,所以只匹配到一条 meta
下一篇介绍,BeautifulSoup 的 css 选择器

更多文章链接:Python 爬虫随笔


- 本笔记不允许任何个人和组织转载
posted @ 2018-09-06 21:01  xpwi  阅读(510)  评论(0编辑  收藏  举报