使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解(新手必学)
为大家介绍下Python爬虫库BeautifulSoup遍历文档树并对标签进行操作的详细方法与函数
下面就是使用Python爬虫库BeautifulSoup对文档树进行遍历并对标签进行操作的实例,都是最基础的内容
需要代码的同学可以添加群624440745
不懂的问题有老司机解决里面还有最新Python教程项目可拿,,一起相互监督共同进步!
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,'lxml')
一、子节点
一个Tag可能包含多个字符串或者其他Tag,这些都是这个Tag的子节点.BeautifulSoup提供了许多操作和遍历子结点的属性。
1.通过Tag的名字来获得Tag
print(soup.head)
print(soup.title)
1
2
<head><title>The Dormouse's story</title></head>
<title>The Dormouse's story</title>
1
2
通过名字的方法只能获得第一个Tag,如果要获得所有的某种Tag可以使用find_all方法
soup.find_all('a')
1
[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]
2.contents属性:将Tag的子节点通过列表的方式返回
head_tag = soup.head
head_tag.contents
1
2
[<title>The Dormouse's story</title>]
1
title_tag = head_tag.contents[0]
title_tag
1
2
<title>The Dormouse's story</title>
1
title_tag.contents
1
["The Dormouse's story"]
1
3.children:通过该属性对子节点进行循环
for child in title_tag.children:
print(child)
1
2
The Dormouse's story
1
4.descendants: 不论是contents还是children都是返回直接子节点,而descendants对所有tag的子孙节点进行递归循环
for child in head_tag.children:
print(child)
```bash
```
for child in head_tag.descendants:
print(child)
<title>The Dormouse's story</title>
The Dormouse's story
5.string 如果tag只有一个NavigableString类型的子节点,那么tag可以使用.string得到该子节点
title_tag.string
1
"The Dormouse's story"
1
如果一个tag只有一个子节点,那么使用.string可以获得其唯一子结点的NavigableString.
head_tag.string
1
head_tag.string
1
如果tag有多个子节点,tag无法确定.string对应的是那个子结点的内容,故返回None
print(soup.html.string)
None
1
6.strings和stripped_strings
如果tag包含多个字符串,可以使用.strings循环获取
for string in soup.strings:
print(string)
1
2
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
Elsie
,
Lacie
and
Tillie
;
and they lived at the bottom of a well.
...
.string输出的内容包含了许多空格和空行,使用strpped_strings去除这些空白内容
for string in soup.stripped_strings:
print(string)
1
2
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
Elsie
,
Lacie
and
Tillie
;
and they lived at the bottom of a well.
...
二、父节点
1.parent:获得某个元素的父节点
title_tag = soup.title
title_tag.parent
1
2
<head><title>The Dormouse's story</title></head>
1
字符串也有父节点
title_tag.string.parent
1
<title>The Dormouse's story</title>
1
2.parents:递归的获得所有父辈节点
link = soup.a
for parent in link.parents:
if parent is None:
print(parent)
else:
print(parent.name)
p
body
html
[document]
三、兄弟结点
sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>",'lxml')
print(sibling_soup.prettify())
1
2
<html>
<body>
<a>
<b>
text1
</b>
<c>
text2
</c>
</a>
</body>
</html>
1.next_sibling和previous_sibling
sibling_soup.b.next_sibling
1
<c>text2</c>
1
sibling_soup.c.previous_sibling
1
<b>text1</b>
1
在实际文档中.next_sibling和previous_sibling通常是字符串或者空白符
soup.find_all('a')
1
[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]
soup.a.next_sibling # 第一个<a></a>的next_sibling是,\n
```bash
‘,\n’
```bash
soup.a.next_sibling.next_sibling
<a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>
1
2.next_siblings和previous_siblings
for sibling in soup.a.next_siblings:
print(repr(sibling))
1
2
',\n'
<a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>
' and\n'
<a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>
';\nand they lived at the bottom of a well.'
for sibling in soup.find(id="link3").previous_siblings:
print(repr(sibling))
1
2
' and\n'
<a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>
',\n'
<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>
'Once upon a time there were three little sisters; and their names were\n'
四、回退与前进
1.next_element和previous_element
指向下一个或者前一个被解析的对象(字符串或tag),即深度优先遍历的后序节点和前序节点
last_a_tag = soup.find("a", id="link3")
print(last_a_tag.next_sibling)
print(last_a_tag.next_element)
;
and they lived at the bottom of a well.
Tillie
1
2
last_a_tag.previous_element
1
' and\n'
1
2.next_elements和previous_elements
通过.next_elements和previous_elements可以向前或向后访问文档的解析内容,就好像文档正在被解析一样
for element in last_a_tag.next_elements:
print(repr(element))
1
2
'Tillie'
';\nand they lived at the bottom of a well.'
'\n'
<p class="story">...</p>
'...'
'\n'
————————————————
注意:很多人学Python过程中会遇到各种烦恼问题解决不了。为此小编建了个Python全栈免费答疑交流.裙 :624440745,不懂的问题有老司机解决里面还有最新Python教程项目可拿,,一起相互监督共同进步!
本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。
使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解(新手必学)的更多相关文章
- 使用requests爬取梨视频、bilibili视频、汽车之家,bs4遍历文档树、搜索文档树,css选择器
今日内容概要 使用requests爬取梨视频 requests+bs4爬取汽车之家 bs4遍历文档树 bs4搜索文档树 css选择器 内容详细 1.使用requests爬取梨视频 # 模拟发送http ...
- bs4--官文--遍历文档树
遍历文档树 还拿”爱丽丝梦游仙境”的文档来做例子: html_doc = """ <html><head><title>The Dor ...
- Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释
这篇文章主要介绍了Pythont特殊语法filter,map,reduce,apply使用方法,需要的朋友可以参考下(1)lambda lambda是Python中一个很有用的语法,它允许你快速定义单 ...
- Python标准库:内置函数hasattr() getattr() setattr() 函数使用方法详解
hasattr(object, name) 本函数是用来判断对象object的属性(name表示)是否存在.如果属性(name表示)存在,则返回True,否则返回False.参数object是一个对象 ...
- Python + Selenium + AutoIt 模拟键盘实现另存为、上传、下载操作详解
前言 在web页面中,可以使用selenium的定位方式来识别元素,从而来实现页面中的自动化,但对于页面中弹出的文件选择框,selenium就实现不了了,所以就需引用AutoIt工具来实现. Auto ...
- Python爬虫之Beautifulsoup模块的使用
一 Beautifulsoup模块介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Be ...
- python爬虫之beautifulsoup的使用
一.Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释:Beautiful Soup提供一些简单的.python式 ...
- 【Python爬虫】BeautifulSoup网页解析库
BeautifulSoup 网页解析库 阅读目录 初识Beautiful Soup Beautiful Soup库的4种解析器 Beautiful Soup类的基本元素 基本使用 标签选择器 节点操作 ...
- Python爬虫系列(六):搜索文档树
今天早上,写的东西掉了.这个烂知乎,有bug,说了自动保存草稿,其实并没有保存.无语 今晚,我们将继续讨论如何分析html文档. 1.字符串 #直接找元素soup.find_all('b') 2.正则 ...
随机推荐
- Egret学习-TiledMap使用
环境说明: 引擎版本:5.2.4 Egret Wing 4.1.6 1.下载依赖,下载地址https://github.com/egret-labs/egret-game-library/tree/m ...
- [bzoj1045] [洛谷P2512] [HAOI2008] 糖果传递
Description 有n个小朋友坐成一圈,每人有ai个糖果.每人只能给左右两人传递糖果.每人每次传递一个糖果代价为1. Input 第一行一个正整数nn<=1'000'000,表示小朋友的个 ...
- java小心机(3)| 浅析finalize()
每天进步一丢丢,连接梦与想 如果你停止就是谷底,如果你还在努力就是上坡 系列文章 java"小心机"(1)[资源彩蛋!] java小心机(2)| 重载和构造器的小细节 预备知识 J ...
- 16、python面对对象之类和继承
前言:本文主要介绍python面对对象中的类和继承,包括类方法.静态方法.只读属性.继承等. 一.类方法 1.类方法定义 使用装饰器@classmethod装饰,且第一个参数必须是当前类对象,该参数名 ...
- GCC编译Win图形程序不显示控制台方法
用VS编译openCV这些有控制台又有图形显示的程序,如果想隐藏控制台,只需要使用一行代码: #pragma comment( linker, "/subsystem:/"wind ...
- Java的String类常用方法
一.构造函数 String(byte[ ] bytes):通过byte数组构造字符串对象. String(char[ ] value):通过char数组构造字符串对象. String(Sting or ...
- python文件、文件夹的相关操作
python文件.文件夹的相关操作 #1.rename()可以完成对文件的重命名 #rename(需要修改的文件名,新的文件名) import os os.rename("readme.tx ...
- HTTP权威指南之URL与资源
前言 web基础中介绍了URI.URL与URN: URI是一类更通用的资源标识符,URL是它的一个子集: URI是一个通用的概念,它主要由URL与URN组成: URL是通过描述资源的位置来标识资源的, ...
- Ubuntu安装openjdk8
sudo apt-get update sudo apt-get install openjdk-8-jdk 通过 which java 找到java安装路径 添加环境变量 sudo vim ~/.b ...
- springboot整合elasticJob实战(纯代码开发三种任务类型用法)以及分片系统,事件追踪详解
一 springboot整合 介绍就不多说了,只有这个框架是当当网开源的,支持分布式调度,分布式系统中非常合适(两个服务同时跑不会重复,并且可灵活配置分开分批处理数据,贼方便)! 这里主要还是用到zo ...