python - getText() 对比 text() 对比 get_text()

标签 python python-3.x beautifulsoup

我有一大块用 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>

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

output.text()

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

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

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

最佳答案

它们非常相似:

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

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

关于python - getText() 对比 text() 对比 get_text(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093875/

相关文章:

python - 如何从字符串列表中获取少数特定字符串?

python - 使用 pivot_table 时应用不同的聚合函数

python - Beautiful Soup 获取 div 中第一个表的数据

python - 从 <a> BeautifulSoup 中提取 href

python - dataReceived() 方法在 python 扭曲框架中混淆行为

python - 将字符串的字符分隔成列表(python)

创建彼此的类对象的 Python 类

python - 在 python 中解析 HTML - lxml 或 BeautifulSoup?其中哪一个更适合什么样的目的?

python - 在特定的 pytest 标记上禁用 autouse fixtures

Python 将 UTF-16 和 UTF-8(?) 的混合格式转换为常规字符串