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

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

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

遍历文档对象

  • 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打印出标签的具体内容,不带有标签,只有内容 固然,若是以为遍历太耗费资源,没有必要遍历的时候,能够使用搜索node

搜索文档对象

  • 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 选择器git

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

<hr>- 本笔记不容许任何我的和组织转载github

相关文章
相关标签/搜索