beautifulsoup4的使用

文本内容 

<html><head><title>The Dormouse's story</title></head>
<body>
<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" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p><p class="story">...</p>

 获取标签

多个标签的情况下之返回第一个标签

soup = BeautifulSoup(open("Index.html"),"lxml")>>> soup.title
<title>The Dormouse's story</title>
>>> soup.title.name
'title'
>>> soup.title.string
"The Dormouse's story"

获取父标签 

>>> soup.title.parent
<head><title>The Dormouse's story</title></head>
>>> soup.title.parent.name
'head'
>>> soup.title.parent.string
"The Dormouse's story"

只返回第一个标签 

>>> soup.p
<p class="title"><b>The Chapter 1 of the Dormouse's story</b></p>
>>> soup.p.name
'p'
>>> soup.p.string
"The Chapter 1 of the Dormouse's story">>> soup.p.parent
<body>
<p class="title"><b>The Chapter 1 of the Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p></body>
>>> soup.a
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
>>> soup.a.name
'a'
>>> soup.a.string
'Elsie'

获取标签的属性值 

>>> soup.p["class"]
['title']
>>> soup.a["href"]
'http://example.com/elsie'
>>> soup.a["id"]

修改和删除标签的属性值 

soup.a["href"] = "how can I see you ?" 
print(soup.a["href"])
# how can I see you ?del soup.a["href"] 
print(soup.a)
# <a class="sister" id="link1">Elsie</a>

根据属性查找标签 

>>> soup.find(href="http://example.com/elsie")
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
>>> soup.find(id="link2")
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>>>> soup.find(class_="sister")
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

find_all() 查找所有标签

>>> soup.find_all("title")
[<title>The Dormouse's story</title>]>>> soup.find_all("p")
[<p class="title"><b>The Chapter 1 of the Dormouse's story</b></p>, <p class="story">Once upon a time there were three little sisters; and their names were<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;and they lived at the bottom of a well.</p>, 
<p class="story">...</p>]>>> soup.find_all("a")
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, 
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, 
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
for link in soup.find_all("a"):print(link["id"],"--",link["class"],"--", link["href"])
"""
link1 -- ['sister'] -- http://example.com/elsie
link2 -- ['sister'] -- http://example.com/lacie 
link3 -- ['sister'] -- http://example.com/tillie
"""
soup.get_text()
"""
The Dormouse's storyThe Chapter 1 of 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.
...
"""

三个对象 

>>> type(soup)
<class 'bs4.BeautifulSoup'>>>> type(soup.p)
<class 'bs4.element.Tag'>>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>

数组获取子标签 

>>> soup.head.contents
[<title>The Dormouse's story</title>]>>> soup.body.contents[3].contents
['Once upon a time there were three little sisters; and their names were\n', <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, ',\n', <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, ' and\n', <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>, ';\nand they lived at the bottom of a well.']>>> soup.body.contents
"""
['\n', <p class="title"><b>The Chapter 1 of the Dormouse's story</b></p>, '\n', <p class="story">Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>, '\n', <p class="story">...</p>]
"""

children获取子标签 

print(soup.body.children," ",type(soup.body.children)) 
# <list_iterator object at 0x0000026C0D7EDBD0>   <class 'list_iterator'>p_3 = soup.body.contents[3].contents
print(p_3)
a_1=p_3[1]
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a># 标签内的文本也是子节点
for child in a_1.children:print(child) # Elsiefor cc in a_1.contents:   # a_1.contents==['Elsie']print(cc)    # Elsie

descendants获取子孙标签 

for child in soup.head.children:print(child)
# <title>The Dormouse's story</title>for dd in soup.head.descendants:print(dd)
# <title>The Dormouse's story</title>
# The Dormouse's story

CSS选择

1. 标签名查找 

print(soup.select("title"))  #[<title>The Dormouse's story</title>]
print(soup.select("b"))      #[<b>The Dormouse's story</b>]

 2. 类名查找

print(soup.select(".sister")) 
"""
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, 
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, 
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
"""

 3. id名查找

print(soup.select("#link1"))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

4. 组合查找 

print(soup.select("p #link3"))
# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

子标签查找

print(soup.select("p > #link3"))
# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

把pascal voc(.xml)格式转为yolo(.txt)格式

单个文件转换

from bs4 import BeautifulSoupimport os def pasvcal_voc_to_yolo(xml_file,class_mapping,output_path):with open(xml_file,"r") as f:soup = BeautifulSoup(f,"xml")width = int( soup.size.width.string )height = int( soup.size.height.string)yolo_format = []for obj in soup.find_all("object"):# class_name = obj.name.string 报错# class_name = obj.find("name").text也可以class_name = obj.find("name").stringif class_name in class_mapping:class_index = class_mapping[class_name]# 也可以xmin = int(obj.find('bndbox').find('xmin').text)xmin = int( obj.bndbox.xmin.string )ymin = int( obj.bndbox.ymin.string )xmax = int( obj.bndbox.xmax.string )ymax = int( obj.bndbox.ymax.string )x_center = (xmin+xmax) / 2 / widthy_center = (ymin+ymax) / 2 / heightbbox_width = (xmax-xmin) / widthbbox_height = (ymax-ymin) / heightyolo_format.append(f"{class_index} {x_center} {y_center} {bbox_width} {bbox_height}")txt_filename = os.path.basename(xml_file).replace(".xml",".txt")output_filename = os.path.join(output_path,txt_filename)with open(output_filename,"w") as f :for label in yolo_format:f.write(f"{label}\n")class_mapping={"car":0
}src = "./0.xml"
dist = os.getcwd()pasvcal_voc_to_yolo(src,class_mapping,dist)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/457796.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

手机柔性屏全贴合视觉应用

在高科技日新月异的今天&#xff0c;手机柔性显示屏作为智能手机市场的新宠&#xff0c;以其独特的可弯曲、轻薄及高耐用性特性引领着行业潮流。然而&#xff0c;在利用贴合机加工这些先进显示屏的过程中&#xff0c;仍面临着诸多技术挑战。其中&#xff0c;高精度对位、应力控…

8. 数据结构—排序

目录 一、插入排序 1&#xff09; 直接插入排序 优化&#xff1a; 折半插入排序 2&#xff09;希尔排序 二、 交换排序 1&#xff09;冒泡排序 2&#xff09;快速排序——递归实现 三、选择排序 1&#xff09;简单选择排序 2&#xff09;堆排序 四、归并排序 五. 各…

论文笔记(五十一)Challenges for Monocular 6-D Object Pose Estimation in Robotics

Challenges for Monocular 6-D Object Pose Estimation in Robotics 文章概括摘要I. 介绍II. 正在进行的研究和常见数据集A. 数据集B. 正在进行的研究问题 III. 未来挑战A. 物体本体B. 可变形和关节物体C. 场景级一致性D. 基准现实性E. 环境影响F. 通用物体操控 IV. 结论 Estim…

Telephony中ITelephony的AIDL调用关系

以Android14.0源码讲解 ITelephony来自framework下的com.android.internal.telephony包下 frameworks/base/telephony/java/com/android/internal/telephony/ITelephony.aidl这个接口用于与Phone交互的界面&#xff0c;主要由TelephonyManager类使用&#xff0c;一些地方仍在…

多元线性回归【正规方程/sklearn】

多元线性回归【正规方程/sklearn】 1. 基本概念1.1 线性回归1.2 一元简单线性回归1.3 最优解1.4 多元线性回归 2. 正规方程求最优解2.1 线性回归的损失函数&#xff08;最小二乘法&#xff09;2.2 推导正规方程2.3 正规方程练习2.4 使用sklearn计算多元线性方程2.5 凸函数 3. 线…

InternVL-1.1: Enhance Chinese and OCR Capabilities

Blog:https://internvl.github.io/blog/2024-01-24-InternVL-1.1/ 指南:https://internvl.readthedocs.io/en/latest/internvl1.1/introduction.html InternVL-Chat-V1-1 结构类似于 LLaVA,包括一个 ViT、一个 MLP 投影器和一个 LLM。如上图所示,我们通过一个简单的 MLP …

JAVA篇之类和对象

目录 一. 面向对象 1.1 面向对象和面向过程 二. 类的定义和使用 2.1 什么是类 2.2 类的定义格式 三. 类的实例化 四. this引用 4.1 this引用的作用 五. 构造方法 5.1 构造方法重载 5.2 通过this调用其他构造方法 5.3 默认初始化 结语 一. 面向对象 Java 是一门面向对…

面向对象与设计模式第二节:设计模式实战

第三章&#xff1a;面向对象与设计模式 第二节&#xff1a;设计模式实战 设计模式是软件工程中的一项重要实践&#xff0c;它为解决常见的设计问题提供了经过验证的解决方案。本课将深入探讨几种常见的设计模式&#xff0c;并通过实际案例分析其在项目中的应用。 1. 每种设计…

JavaEE初阶---文件IO总结

文章目录 1.文件初识2.java针对于文件的操作2.1文件系统的操作---file类2.2文件内容的操作---流对象的分类2.4字符流的操作》文本文件2.4.1异常的说明2.4.2第一种文件内容的读取方式2.4.3第二种读取方式2.4.4close的方法的介绍2.4.5close的使用优化操作2.4.6内容的写入 2.3字节…

无需依赖闭源模型!司南CompassJudger为AI评测带来新选择

前沿科技速递&#x1f680; 近期&#xff0c;司南OpenCompass团队发布了一款开源的全能评价模型——CompassJudger。这是全球首个全能开源的 All-in-one Judge Model&#xff0c;不仅支持主流的双向对比&#xff08;pair-wise&#xff09;和单向评分&#xff08;point-wise&…

软件工程--需求分析与用例模型

面向对象分析(ObjectOrientedAnalysis&#xff0c;简称OOA) 分析和理解问题域&#xff0c;找出描述问题域所需的类和对象&#xff0c;分析它们的内部构成和外部关系&#xff0c;建立独立于实现的OOA模型&#xff0c;暂时忽略与系统实现有关的问题。 主要使用UML中的以下几种图…

全球知名度最高的华人起名大师颜廷利:世界顶级思想哲学教育家

全国给孩子起名最好的大师颜廷利教授在其最新的哲学探索中&#xff0c;提出了《升命学说》这一前沿理论观点&#xff0c;该理论不仅深刻地回应了古今中外众多哲学流派和思想体系的精髓&#xff0c;还巧妙地融合了实用主义、理想主义以及经验主义的核心理念。通过这一独特的视角…

我准备写一份Stable Diffusion入门指南-part1

我准备写个SD自学指南&#xff0c;当然也是第一次写&#xff0c;可能有点凌乱&#xff0c;后续我会持续更新不断优化&#xff0c;我是生产队的驴&#xff0c;欢迎监督。 Stable Diffusion WebUI 入门指南 Stable Diffusion WebUI 是一款基于 Stable Diffusion 模型的用户界面…

力扣 中等 740.删除并获得点数

文章目录 题目介绍题解 题目介绍 题解 由题意可知&#xff0c;在选择了数组中元素 a 后&#xff0c;该元素以及所有等于 a−1 和 a1 的元素都会从数组中删去&#xff0c;并获得 a 的点数。若还有多个值为 a的元素&#xff0c;由于所有等于 a−1 或 a1 的元素已经被删除&#x…

三种材料的金相图及金相图解析材料

3. 二&#xff0e;不同温度下三种材料&#xff08;铸铁&#xff0c;铝&#xff0c;低碳钢&#xff09;的低温脆性&#xff0c;相关材料&#xff0c;文献引用 三&#xff0e;三种材料在汽车制造中可能的应用 &#xff08;如捷豹用铝合金降低车身重量&#xff09;.三种材料哪个材…

Linux: Shell编程入门

Shell 编程入门 1 ) Shell 概念 shell 是 在英语中 壳, 外壳的意思可以把它想象成嵌入在linux这样的操作系统里面的一个微型的编程语言不像C语言, C 或 Java 等编程语言那么完整&#xff0c;它可以帮我们完成很多自动化任务例如保存数据监测系统的负载等等&#xff0c;我们同样…

AI博士人手10篇顶会,遭质疑。。。

B站&#xff1a;啥都会一点的研究生公众号&#xff1a;啥都会一点的研究生 AI科技圈又发生了啥新鲜事&#xff1f; “稚晖君”灵犀X1全球开源&#xff0c;推动人形机器人技术共享 智元机器人宣布其人形机器人灵犀X1正式面向全球开源&#xff0c;提供了超过1.2GB的软硬件全套…

【LeetCode】11.盛最多水的容器

思路&#xff1a; 利用双指针法进行移动&#xff0c;一个在头一个在尾&#xff0c;此时宽度最宽&#xff0c;当宽度缩小时&#xff0c;高度发生变化&#xff0c;从而可以找到最大值。 代码&#xff1a; int maxArea(int* height, int heightSize) {int* left height;int* …

android——渐变色

1、xml的方式实现渐变色 效果图&#xff1a; xml的代码&#xff1a; <?xml version"1.0" encoding"utf-8"?> <shape xmlns:android"http://schemas.android.com/apk/res/android"xmlns:tools"http://schemas.android.com/tools…

Java常见数据结构

数组 数组的特性存储空间是连续的长度是不可变的只能存储 相同的类型(不严谨)可以通过下标访问数组的内容 a[10] 复杂度是O1每个元素的默认是为零值 0 null false -> 一个对象的基本的数据域的初始化也是这样的 Student 类中的username属性 默认值 链表 查找麻烦 插入和删…