.text 和 .get_text() 之间的差异

Differences between .text and .get_text()

BeautifulSoup中,.text.get_text()有区别吗?

获取元素的文本应该首选哪个?

>>> from bs4 import BeautifulSoup
>>>
>>> html = "<div>text1 <span>text2</span><div>"
>>> soup = BeautifulSoup(html, "html.parser")
>>> div = soup.div
>>> div.text
'text1 text2'
>>> div.get_text()
'text1 text2'

看起来像.text is just a property that calls get_text。因此,不带参数调用 get_text.text 是一样的。然而,get_text 也可以支持各种关键字参数来改变它的行为方式(separatorstriptypes)。如果您需要对结果进行更多控制,那么您需要函数形式。