getText() 与 text() 与 get_text()

Pro*_*ova 2 python beautifulsoup python-3.x

我用 bs4 提取了一大块 html,如下所示

<div class="a-section a-spacing-small" id="productDescription">
<!-- show up to 2 reviews by default -->
<p>Satin Smooth Universal Protective Wax Pot Collars by Satin Smooth</p>
</div>
Run Code Online (Sandbox Code Playgroud)

提取我使用的文本 text.strip()

output.text()
Run Code Online (Sandbox Code Playgroud)

它给了我输出 "TypeError: 'str' object is not callable"

当我使用output.get_text()and 时output.getText(),我得到了想要的文本

这3个有什么区别?为什么 get_text() 和 getText() 给出相同的输出?

L3v*_*han 5

它们非常相似:

  • .get_text 是一个将标签文本作为字符串返回的函数
  • .text是一个调用的属性get_text(所以它是相同的,除非你不使用括号)
  • .getText 是一个别名 get_text

我会.text尽可能使用,.get_text(...)当您需要传递自定义参数(例如foo.get_text(strip=True, seperator='\n'))。