首页 > 解决方案 > Python-for循环x次,循环中包含信息

问题描述

我正在尝试循环遍历一条信息 ax 次,但我似乎无法使其与 range() 或 isslice 一起使用。我想说循环中的代码只循环了 x 次。

我想循环通过 x 次的循环:

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()

我已经阅读了很多堆栈溢出问题,但我可能没有足够的经验来针对我的情况实施它。我已经尝试了几件事,但到目前为止没有任何效果。

我尝试了以下方法:

(“reacties”是它需要循环的 x 次的变量)

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

和:

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

标签: pythonloopsfor-looprange

解决方案


您可以合并enumerate功能。 https://docs.python.org/3/library/functions.html#enumerate 例如:

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

推荐阅读