BeautifulSoup中的.text方法和get_text()方法的区别
来源:互联网 发布:淘宝店铺重开 编辑:程序博客网 时间:2024/05/29 18:05
转自https://www.crifan.com/python_beautifulsoup_string_vs_text/
【背景】
是别人问我的:
BeautifulSoup 4中,soup.string和soup.text何有区别。
【折腾过程】
1.去beautifulsoup的官网:
bs3:
http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html
和
bs4
http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text
找了半天,都没有soup.text的用法。
2.但是该人的确使用代码:
price_div = li.find('div' , {'class':'pPrice clearfix'})vs.append(price_div.em.text.split('\n')[5].strip().encode('gbk'))
是可以运行的。
3.开始我以为此处其html中有个特殊的em和text节点呢,类似于:
<html> <em> <text>xxx</text> </em></html>
结果后来证实,其html中只有em,em其下没有text这个tag节点。
4.官网的文档中,和.text最接近的,也只有:
get_text()
5.后来下载到最新源码
http://www.crummy.com/software/BeautifulSoup/bs4/download/4.3/beautifulsoup4-4.3.1.tar.gz
解压后,看到:
\beautifulsoup4-4.3.1\bs4\element.py
中,有对应的代码:
@property def stripped_strings(self): for string in self._all_strings(True): yield string def get_text(self, separator=u"", strip=False, types=(NavigableString, CData)): """ Get all child strings, concatenated using the given separator. """ return separator.join([s for s in self._all_strings( strip, types=types)]) getText = get_text text = property(get_text)
所以,结论就很明显了。
【总结】
beautifulsoup中,对外接口,没有提供text这个属性,只有string这个属性值;
beautifulsoup内部才有text这个属性,只供内部使用 –> 如果你想要用text值,应该调用对应的get_text()
而你之所有能够直接用soup.text而没报错,应该是和python的class的property没有变成private有关系 –>导致你外部也可以访问到这个,本身是只供内部使用的属性值-> 这个要抽空深究了。
转载请注明:在路上 »【整理】BeautifulSoup中的.string和.text的区别
那么get_text()h和string有什么区别的,我自己试了一下,
html="'
<html><head><title >The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>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>,
<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>
'''
发现如果是对a标签进行用get_text方法,返回的是空白
而如果是.string方法,对任何标签都能获得其中注释的内容,即Elsie
- BeautifulSoup中的.text方法和get_text()方法的区别
- Beatifulsoup 中soup的get_text()方法
- text和content方法的区别
- jquery 中的html()方法与text()的区别
- python requests的content和text方法的区别
- python requests的content和text方法的区别
- python requests的content和text方法的区别(转)
- winform中的ComboBox同时设置text和value的方法
- jquery中html()和text()方法区别
- Ubuntu下python的BeautifulSoup和Mechanize安装方法
- Mac OS X安装Scrapy、PIL和BeautifulSoup的方法
- Jquery--text()与html()方法的区别
- jquery html-与-text方法的区别
- html()方法和text()方法有区别嘛?
- C#中的抽象方法和虚方法的区别
- html中的get方法和post方法的区别
- JAVA中的静态方法 和 实例方法的区别
- HttpServletRequest中的getAttribute方法和getParameter方法的区别
- 实验一:Linux操作系统的安装
- Hdu1969-Pie-【二分】
- RGBD_SLAM(1)
- 八种架构设计模式及其优缺点概述
- 二叉树最小深度探究
- BeautifulSoup中的.text方法和get_text()方法的区别
- 2-sat
- 浅谈八皇后问题
- 某笔试题(一)获取20个随机不重复的字符
- JavaWeb
- Spring bean id相同引发的故障
- demo_3. Python的函数嵌套
- nodejs和python 简单爬取百度图片保存在本地
- 编译开关学习