【问题标题】:method vs property What is faster?方法 vs 属性哪个更快?
【发布时间】:2020-01-25 05:47:16
【问题描述】:

bs4.BeautifulSoup 中有bs4.element.Tag 对象。 它有财产text 它有方法get_text。 两者都返回关于text(str).的相同结果

我对

产生了好奇

“方法与属性”

哪种访问速度更快?

我通过 time.time() 检查我的本地,但在每次运行中,结果都会改变。

这是一种无用的好奇心吗?

【问题讨论】:

  • time.time() 不同运行的结果会有所不同。不过差别不会太大吧?

标签: python class methods beautifulsoup properties


【解决方案1】:

text 属性只能按原样给出文本。

get_text() 可以做一些“定制”。就像在不同标签的文本之间插入分隔符或从字符串的末尾去除空格。


get_text() 接受以下参数:

  • separator:在各个标签的文本之间插入一个字符串作为分隔符。
  • strip: 去掉标签文本末尾的空格。

考虑

html_str = """
<div>
\nHello
  <span>World!</span>
  <a href="">Click here</a>
</div>
"""
soup = BeautifulSoup(html_str, 'html.parser')

如果我们考虑&lt;div&gt;标签的文本像

soup.text

应该是

'\n\n\nHello\n  World!\nClick here\n\n'

如果使用strip 参数

>>> soup.get_text(strip=True)
'HelloWorld!Click here'

如果使用separator 参数

>>> soup.get_text(separator='**')
'\n**\n\nHello\n  **World!**\n**Click here**\n**\n'

如果同时使用separatorstrip

>>> soup.get_text(separator='**', strip=True)
'Hello**World!**Click here'

运行时间似乎大致相同。

%timeit soup.text
4.16 µs ± 56.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit soup.get_text(strip=True)
5.38 µs ± 154 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit soup.get_text(separator='**')
4.16 µs ± 53.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit soup.get_text(separator='**', strip=True)
5.45 µs ± 213 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 2013-03-02
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    相关资源
    最近更新 更多