AmagicalFishy AmagicalFishy - 4 years ago 106
Python Question

What usage is the anonymous function in findAll?

I'm parsing some tables w/ BeautifulSoup, and came across an easy way to pick out the table's

tags. Try as I might, though, I don't know why this particular bit of code works (specifically: the very last line).

response = urlopen(url)
table = SoupStrainer('table',{'border': 0, 'cellpadding': 5})
soup = BeautifulSoup(html, parseOnlyThese = table)
soup.findAll(lamba tag: == "td")

What's the point of defining the anonymous function,
? I've tried
soup.findAll(name == "td")
which doesn't work, but
soup.findAll(lambda grop: == "td")
works. How is this lambda function interacting with BeautifulSoup and why do I need it? Is there another way of writing the same code that makes things a bit more clear?

Answer Source

The first argument to find*() functions in BeautifulSoup can be a function.

In this particular case:

soup.findAll(lambda tag: == "td")

is really an overkill and is equivalent to:


A function can also be used to filter a specific attribute, for example:

soup.find_all("a", href=lambda href: href and href.startswith("http"))

Some of the real-world use cases:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download