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

原创粉丝点击