bs4 string与text的区别
用python写爬虫时,BeautifulSoup真是解析html,快速获取所需数据的神器。
这个美味汤使唤起来,屡试不爽。
在用find()方法找到特定的tag后,想获取里面的文本,可以用.text属性或者.string属性。
在很多时候,两者的返回结果一致,但其实两者是有区别的。
.string的资料很多,.text的资料比较少。
遍寻中文世界没有满意的答案,直接google在stock overflow中找到了很满意的解答:
.string
on a Tag
type object returns a NavigableString
type object. On the other hand, .text
gets all the child strings and return concatenated using the given separator. Return type of .text is unicode
object.
From the documentation, A NavigableString
is just like a Python Unicode
string, except that it also supports some of the features described in Navigating the tree and Searching the tree.
From the documentation on .string
, we can see that, If the html is like this,
-
<td>Some Table Data</td>
-
<td></td>
Then, .string
on the second td will return None
. But .text
will return and empty string which is a unicode
type object.
For more convenience,
string
- Convenience property of a
tag
to get the single string within this tag. - If the
tag
has a single string child then the return value is that string. - If the
tag
has no children or more than one child the return value isNone
- If this
tag
has one child tag return value is the 'string' attribute of the child tag, recursively.
And text
- Get all the child strings and return concatenated using the given separator.
If the html
is like this:
-
1、<td>some text</td>
-
2、<td></td>
-
3 、<td><p>more text</p></td>
-
4、<td>even <p>more text</p></td>
-
.string
on the four td
will return,
-
1、some text
-
2、None
-
3、more text
-
4、None
.text
will give result like this
-
1、some text
-
-
2、more text
-
3、even more text
通过以上的举例,可以很清楚的发现,.find和.string之间的差异:
第一行,在指定标签td,没有子标签,且有文本时,两者的返回结果一致,都是文本
第二行,在指定标签td,没有子标签,且没有文本时,.string返回None,.text返回为空
第三行,在指定标签td,只有一个子标签时,且文本只出现在子标签之间时,两者返回结果一致,都返回子标签内的文本
第四行,最关键的区别,在指定标签td,有子标签,并且父标签td和子标签p各自包含一段文本时,两者的返回结果,存在很大的差异
.string返回为空,因为文本数>=2,string不知道获取哪一个
.text返回的是,两段文本的拼接。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人