日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

BeautifulSoup中的.text方法和get_text()方法的区别

發布時間:2025/3/19 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()方法的区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。