0

I am trying to loop through a piece of info for a x amount of times, but I can't seem to make it work with range() or isslice. I want to be able to say that the code within the loop are only looped x amount of times.

The loop I would like to loop trough x amount of times:

html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
x = soup.find("div", class_="object-list-items-container")


for child in x.findChildren("section", recursive=False):
        if "U heeft gereageerd" in child.text:
            continue
        else:
            house_id = child.find("div", {'class': 'ng-scope'}).get("id")
            driver.find_element_by_id(house_id).click()

I've read quite some stack overflow questions but i'm probably not experienced enough to implement it for my situation. I have tried a couple of things, but nothing worked so far.

I've tried the following:

("reacties" is the variable for the x amount of times it needs to loop)

for i in range(reacties):
    for child in x.findChildren("section", recursive=False):
        if "U heeft gereageerd" in child.text:
            continue
        else:
          ...........

and:

for i in range(reacties):
    child= x.findChildren("section", recursive=False)
    if "U heeft gereageerd" in child.text:
         continue
    else:
        ...............
Grasmat
  • 75
  • 6

3 Answers3

2

You can incorporate enumerate functionality. https://docs.python.org/3/library/functions.html#enumerate For example:

for count, child in enumerate(x.findChildren("section", recursive=False)):
    If count > reacties:
        break
    if "U heeft gereageerd" in child.text:
        continue
    else:
        ...
George
  • 254
  • 2
  • 6
1

This will iterate n times, based on shortest iterator.

for i, child in zip(range(x), x.findChildren("section", recursive=False)):
    if "U heeft gereageerd" in child.text:
         continue
    else:
        ...............
rozumir
  • 845
  • 9
  • 20
-1

Just make an iterator.

import itertools

it = itertools.repeat(x.findChildren("section", recursive=False), times=n)

for child in it:
    #do your job
  • The goal is to use the first `n` items contained within `x.findChildren("section", recursive=False)`; **not** to use `x.findChildren("section", recursive=False)` `n` times. – Karl Knechtel Jul 30 '22 at 00:58