Python_爬虫_BeautifulSoup网页解析库
2024-10-07 22:12:18
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))) #前面的兄弟节点
最新文章
- Ionic + AngularJS
- 关于OpenCart的一个小建议
- DevExpress ChartControl大数据加载时有哪些性能优化方法
- WPS2013三合一全套精品视频教程-【word,excel,powerpoint】
- 浪潮之巅IT那点事之一——AT&;T的兴衰
- C++Primer 第十一章
- Xcode 7在支持ipad的设备中需要支持分屏!
- linux挂载问题解决
- zDialog无法获取未定义或 null 引用的属性“_dialogArray”
- Screen-Space Bent Cones (SSBC) in Unity5
- 用Set中元素做条件查询
- IOS开发小记-内存管理
- iOS回顾笔记( 01 )
- CentOS7下安装GitLab
- WebGL three.js学习笔记 使用粒子系统模拟时空隧道(虫洞)
- 关于typecho0.9代码高亮与数学公式支持
- python基础一 ------如何统计一个列表元素的频度
- webpack配置说明
- 浅谈分词算法(3)基于字的分词方法(HMM)
- Mysql Federated For Windows
热门文章
- js拖拽上传 文件上传之拖拽上传
- spring boot:actuator的安全配置:使用spring security做ip地址限制(spring boot 2.3.2)
- ansible通过yum/dnf模块给受控机安装软件(ansible2.9.5)
- <;article>;
- Python字典的初识、增删改查及嵌套
- 零基础了解Python的用途
- 联赛模拟测试22 B. 分组配对 倍增+二分
- day02初识判断和循环
- axb_2019_heap-format_string + off-by-one
- List集合,对象根据某个相同的属性,合并另外属性