【背景】
是别人问我的:
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.但是该人的确使用代码:
1 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节点呢,类似于:
1 2 3 4 5 | < 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
中,有对应的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @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有关系 –>导致你外部也可以访问到这个,本身是只供内部使用的属性值-> 这个要抽空深究了。