1

This is my code:

#!/usr/bin/env python

from requests_html import AsyncHTMLSession


async def get_link(url):
    r = await asession.get(url)
    return r


if __name__ == "__main__":
    asession = AsyncHTMLSession()

    results = asession.run(
        lambda: get_link("https://www.digitalocean.com/blog/2/"),
        lambda: get_link("https://www.digitalocean.com/blog/3/"),
        lambda: get_link("https://www.digitalocean.com/blog/4/"),
        lambda: get_link("https://www.digitalocean.com/blog/5/"),
        lambda: get_link("https://www.digitalocean.com/blog/6/"),
        lambda: get_link("https://www.digitalocean.com/blog/7/"),
        lambda: get_link("https://www.digitalocean.com/blog/8/"),
        lambda: get_link("https://www.digitalocean.com/blog/9/"),
    )

    [print(result.html.absolute_links) for result in results]

The blog links are incrementing by 1.

How do I rewrite the code so that I can use a variable for looping over the numbers from 2 to 9?
The aim is to avoid the repetition of the lambda lines.

Diggy.
  • 6,744
  • 3
  • 19
  • 38
GMaster
  • 1,431
  • 1
  • 16
  • 27

1 Answers1

1

You can use the unpacking functionality of the asterisk like so:

results = asession.run(
    *(lambda: get_link(f"https://www.digitalocean.com/blog/{i}/") for i in range(2, 10))
)
Diggy.
  • 6,744
  • 3
  • 19
  • 38
  • 1
    Why unpack the lambda expressions into a list which is then unpacked again? This should work too: `results = asession.run(*(lambda: get_link(f"https://www.digitalocean.com/blog/{i}/") for i in range(2, 10)))` – mhawke Feb 07 '21 at 12:16
  • 1
    Good, now I feel that I can upvote your answer. – mhawke Feb 07 '21 at 12:21