BeautifulSoup中的.text方法和get_text()方法的区别
轉自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
中,有對應的代碼:
@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)所以,結論就很明顯了。
?
【總結】
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()方法的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解python的with as 语句
- 下一篇: Html中框架的使用