【问题标题】:Why Python BeautifulSoup object is callable? Where is the definition?为什么 Python BeautifulSoup 对象是可调用的?定义在哪里?
【发布时间】:2020-04-10 05:11:17
【问题描述】:

下面代码中的bb和cc是相等的,为什么会这样呢?汤是一个对象,为什么它可以在这里接受另一个参数'a'? soup('a') 这里是函数调用还是另一个类/对象初始化?如果是函数调用,我在类中没有找到call定义。我希望这个问题很清楚。谢谢。

from bs4 import BeautifulSoup
soup = BeautifulSoup("<html><a href='bla'>sss</a><a>cc</a></html>", 'html.parser')
bb = soup('a')
cc = soup.find_all('a')

【问题讨论】:

  • 在实践中,如果他们给出相同的结果,我们是否应该总是更喜欢soup('a') 而不是soup.find_all('a')?

标签: python beautifulsoup callable


【解决方案1】:

好吧,实际上没有区别,调用tagaliasfindAll

查看source code

def __call__(self, *args, **kwargs):
    """Calling a tag like a function is the same as calling its
    find_all() method. Eg. tag('a') returns a list of all the A tags
    found within this tag."""
    return self.find_all(*args, **kwargs)

几乎developers 使用findAll 的原因是因为它实际上更具可读性。

【讨论】:

  • 非常感谢,没想到call可以定义在tag class下,以为一定是BeautifulSoup init下。
猜你喜欢
  • 2013-05-29
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2020-10-02
相关资源
最近更新 更多