Search code examples
pythonpython-3.xfor-loopbeautifulsoupnested-loops

Nested print in a nested loop in python


How can I create outputs created in two for loops?

What I would like to have:

Name1
Adress1

Name2
Adress2

..

What I get:

Name1
Name2

Adress1
Adress2

I have already tried a lot and brought back to the initial situation.

The names and the adresses are parsed from a HTML document, and written with the for loops into a txt file. (in the first step to the console)

I thank you in advance!

    with urllib.request.urlopen("file:///C:/Users/x/Desktop/test.html") as url:
        soup = BeautifulSoup(url, "html.parser")
        for name in soup.findAll("div", { "class" : "name m08_name" }):
            print(name.get_text())
        for adress in soup.findAll("div", { "class" : "adresse m08_adresse" }): 
            print(adress.get_text())     

Solution

  • You need just to save your partial results and then zip them togheter.

    Note that you have to be sure that the number of names is exactly equal to the number of addresses.

    with urllib.request.urlopen("file:///C:/Users/x/Desktop/test.html") as url:
        soup = BeautifulSoup(url, "html.parser")
    
        names = [name.get_text() for name in soup.findAll("div", { "class" : "name m08_name" })]
        addresses = [address.get_text() for adress in soup.findAll("div", { "class" : "adresse m08_adresse" })]
        for line in zip(names, addresses):
            print("%s\n%s" % line)