最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【整理】BeautifulSoup中的.string和.text的区别

BeautifulSoup crifan 13194浏览 0评论

【背景】

是别人问我的:

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的区别

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.170 seconds, using 22.07MB memory