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

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 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%E7%88%AC%E8%99%AB/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 爬虫随笔


- 本笔记不允许任何个人和组织转载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肖朋伟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值