且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.text和.get_text()之间的区别

更新时间:2023-12-04 12:00:52

.text 只是一个调用 get_text 的属性。因此,不带参数调用 get_text .text 是一样的。但是, get_text 也可以支持各种关键字参数来改变它的行为方式( separator> $ c>, strip types )。如果你需要更多的控制结果,那么你需要功能表单。


In BeautifulSoup, is there any difference between .text and .get_text()?

Which one should be preferred for getting element's 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'

It looks like .text is just a property that calls get_text. Therefore, calling get_text without arguments is the same thing as .text. However, get_text can also support various keyword arguments to change how it behaves (separator, strip, types). If you need more control over the result, then you need the functional form.