BeautifulSoup中的.text方法和get_text()方法的区别
轉(zhuǎn)自https://www.crifan.com/python_beautifulsoup_string_vs_text/
【背景】
是別人問(wèn)我的:
BeautifulSoup 4中,soup.string和soup.text何有區(qū)別。
【折騰過(guò)程】
1.去beautifulsoup的官網(wǎng):
bs3:
http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html
和
bs4
http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text
找了半天,都沒(méi)有soup.text的用法。
2.但是該人的確使用代碼:
price_div = li.find('div' , {'class':'pPrice clearfix'}) vs.append(price_div.em.text.split('\n')[5].strip().encode('gbk'))是可以運(yùn)行的。
3.開(kāi)始我以為此處其html中有個(gè)特殊的em和text節(jié)點(diǎn)呢,類(lèi)似于:
<html><em><text>xxx</text></em> </html>結(jié)果后來(lái)證實(shí),其html中只有em,em其下沒(méi)有text這個(gè)tag節(jié)點(diǎn)。
4.官網(wǎng)的文檔中,和.text最接近的,也只有:
get_text()
5.后來(lái)下載到最新源碼
http://www.crummy.com/software/BeautifulSoup/bs4/download/4.3/beautifulsoup4-4.3.1.tar.gz
解壓后,看到:
\beautifulsoup4-4.3.1\bs4\element.py
中,有對(duì)應(yīng)的代碼:
@propertydef stripped_strings(self):for string in self._all_strings(True):yield stringdef 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_texttext = property(get_text)所以,結(jié)論就很明顯了。
?
【總結(jié)】
beautifulsoup中,對(duì)外接口,沒(méi)有提供text這個(gè)屬性,只有string這個(gè)屬性值;
beautifulsoup內(nèi)部才有text這個(gè)屬性,只供內(nèi)部使用 –> 如果你想要用text值,應(yīng)該調(diào)用對(duì)應(yīng)的get_text()
而你之所有能夠直接用soup.text而沒(méi)報(bào)錯(cuò),應(yīng)該是和python的class的property沒(méi)有變成private有關(guān)系 –>導(dǎo)致你外部也可以訪(fǎng)問(wèn)到這個(gè),本身是只供內(nèi)部使用的屬性值-> 這個(gè)要抽空深究了。
轉(zhuǎn)載請(qǐng)注明:在路上 ? 【整理】BeautifulSoup中的.string和.text的區(qū)別
那么get_text()h和string有什么區(qū)別的,我自己試了一下,
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>
'''
發(fā)現(xiàn)如果是對(duì)a標(biāo)簽進(jìn)行用get_text方法,返回的是空白
而如果是.string方法,對(duì)任何標(biāo)簽都能獲得其中注釋的內(nèi)容,即Elsie
總結(jié)
以上是生活随笔為你收集整理的BeautifulSoup中的.text方法和get_text()方法的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 理解python的with as 语句
- 下一篇: Html中框架的使用