BeautifulSoup网页解析库

from bs4 import BeautifulSoup

0.BeautifulSoup网页解析库包含 的 几个解析器

  • Python标准库【主要,系统自带;】

    使用方法: BeautifulSoup(markup,"html.parser")【注:markup是html文档】

    Python的内置标准库

    案例:


from bs4 import BeautifulSoup soup = BeautifulSoup.(html,'html.parser') print(soup.title.string)
  • lxmlHTML解析器

    BeautifulSoup(markup,'lxml)

    速度快、需要安装C语言库

  • lxml XML解析器

    使用方法:BeautifulSoup(markup,"xml")

    速度快,唯一支持XML的解析器、需要安装C语言库

  • html5lib

    BeautifulSoup(markup,"html5lib")

    容错性好,以浏览器的形式解析文档,生成html5格式的文档,但是速度慢

1.BeautifulSoup基本使用



#!/usr/bin/env python
# -*- coding:utf-8 -*- html="""
<html>
<head>
<title>The Domouse's story</title>
</head>
<body>
<p class="title" name="Domouse"><b>The Domouse's story</b></p>
<p class="story">Once upon a time there were three little sisters;and their names were</p>
<a href="http://www.baidu.com">百度</a>
<p class="story">...</p>
</body>
</html>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
#获取标签正文内容
print("标签内正文内容:" + soup.title.name)
#获取属性内容
print("属性内容" + soup.p.attrs['name'])
#获取内容
print("获取内容" + soup.p.string)
#获取嵌套内容(多个筛选条件)
print("获取嵌套内容" + soup.head.title.string)
#子节点 和 孙节点【重要,,当目标标签没有id 或 class时候必须用这个】
print("子节点" + soup.p.contents) #全部子节点,返回的是列表形式
print("子节点" + soup.p.contents[2]) #第三个一级子节点,不管是什么标签
#1. 子节点#子节点【迭代器,只能用循环形式拿到数据】
soup = BeautifulSoup(html,"lxml")
print(soup.p.children)
for i,child in enumerate(soup.p.children):
print(i,child)
#2.子孙节点
soup = BeautifulSoup(html,"lxml")
print(soup.p.descendants)
for i,child in enumerate(soup.p.descendants):
print(i,child)
#父节点 和 祖先借点
print(list(enumerate("父节点:" + soup.a.parent))) #父节点
print(list(enumerate("祖父节点:" + soup.a.parent))) #祖父点
#获取兄弟节点 print("后面的兄弟节点" + list(enumerate(soup.a.next_siblings))) #后面的兄弟节点
print("前面的兄弟节点" + list(enumerate(soup.a.previous_slblings))) #前面的兄弟节点

最新文章

  1. Ionic + AngularJS
  2. 关于OpenCart的一个小建议
  3. DevExpress ChartControl大数据加载时有哪些性能优化方法
  4. WPS2013三合一全套精品视频教程-【word,excel,powerpoint】
  5. 浪潮之巅IT那点事之一——AT&amp;T的兴衰
  6. C++Primer 第十一章
  7. Xcode 7在支持ipad的设备中需要支持分屏!
  8. linux挂载问题解决
  9. zDialog无法获取未定义或 null 引用的属性“_dialogArray”
  10. Screen-Space Bent Cones (SSBC) in Unity5
  11. 用Set中元素做条件查询
  12. IOS开发小记-内存管理
  13. iOS回顾笔记( 01 )
  14. CentOS7下安装GitLab
  15. WebGL three.js学习笔记 使用粒子系统模拟时空隧道(虫洞)
  16. 关于typecho0.9代码高亮与数学公式支持
  17. python基础一 ------如何统计一个列表元素的频度
  18. webpack配置说明
  19. 浅谈分词算法(3)基于字的分词方法(HMM)
  20. Mysql Federated For Windows

热门文章

  1. js拖拽上传 文件上传之拖拽上传
  2. spring boot:actuator的安全配置:使用spring security做ip地址限制(spring boot 2.3.2)
  3. ansible通过yum/dnf模块给受控机安装软件(ansible2.9.5)
  4. &lt;article&gt;
  5. Python字典的初识、增删改查及嵌套
  6. 零基础了解Python的用途
  7. 联赛模拟测试22 B. 分组配对 倍增+二分
  8. day02初识判断和循环
  9. axb_2019_heap-format_string + off-by-one
  10. List集合,对象根据某个相同的属性,合并另外属性