2015-11-06 51 views
1

我用requests在Python中發出請求。Python的計數數字或在刮頁上的字母

然後我用bs4來選擇想要的div。我現在要算在該div文本的長度,但我把它弄出來的字符串包括所有的標籤太多,例如:

<div><a class="some_class">Text here!</a></div> 

我想只能算Text here!,沒有所有的diva標籤。

任何人都有任何想法我可以做到這一點?

回答

7

你的意思是:

tag.text 

tag.string 

tag意味着你發現使用soup.find()標籤。查詢the document瞭解更多詳情。


下面是一個簡單的演示,可以幫助你瞭解這是什麼意思:

>>> from bs4 import BeautifulSoup 
>>> soup = BeautifulSoup('<html><body><div><a class="some_class">Text here!</a></div></body></html>', "html.parser") 
>>> tag = soup.find('div') 
>>> tag 
<div><a class="some_class">Text here!</a></div> 
>>> tag.string 
'Text here!' 
>>> tag.text 
'Text here!' 
>>> 

關於算文本的長度,你的意思是使用len()這裏?

>>> tag.text 
'Text here!' 
>>> len(tag.text) 
10