Luk*_*uka 1 html python beautifulsoup bs4
我在Python中发出请求requests.
然后我bs4用来选择想要的div.我现在想要计算该div中文本的长度,但是我从中获取的字符串也包括所有标记,例如:
<div><a class="some_class">Text here!</a></div>
Run Code Online (Sandbox Code Playgroud)
我想只计算Text here!,没有所有div和a标签.
任何人都知道我该怎么做?
你的意思是:
tag.text
Run Code Online (Sandbox Code Playgroud)
要么
tag.string
Run Code Online (Sandbox Code Playgroud)
tag表示您找到的标记soup.find().查看文档以获取更多详细信息.
这是一个简单的演示,可以帮助您理解我的意思:
>>> 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!'
>>>
Run Code Online (Sandbox Code Playgroud)
关于计算文本的长度,你的意思是len()在这里使用吗?
>>> tag.text
'Text here!'
>>> len(tag.text)
10
Run Code Online (Sandbox Code Playgroud)