Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need an explanation for a web scraping lambda function in Python

I’m doing Web Scraping in Python and I’ve found this :

products = soup.find_all('li')
products_list = []
for product in products:
    name = product.h2.string
    price = product.find('p', string=lambda s: 'Price' in s).string
    products_list.append((name, price))

I’d like to understand the lambda function in this case, thank you so much.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are creating a lambda (anonymous) function, which takes s as an argument and then checks if string "Price" is in the s or you can say if s contains string "Price". It will return True or False based on that.

Also, you are storing that function inside string variable. So, you can call that lambda function by that variable: string(s).

Here’s an example (if it helps):


>>> # Create lambda function and store inside `string`
>>> string = lambda s: "Price" in s
>>> # Check `string` indeed a lambda function
>>> string
<function <lambda> at 0x7f4c0afa1630>
>>>
>>> # Call the lambda function with an argument
>>> # Inside lambda function, now, `s = "Hello, World"` !
>>> # It will check this: `"Price" in s`, it's not:
>>> string("Hello, World")
False
>>> # Now, `s = "What is the price of milk?"`
>>> # "Price" and "price" are not same !
>>> string("What is the price of milk?")
False
>>> string("Price of milk is $69.")
True

This lambda function is same as this:

def string(s):
    return "Price" in s
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading