【问题标题】:Python- For loop for x amount of times, with info in the loopPython-for循环x次,循环中包含信息
【发布时间】:2021-04-08 20:12:12
【问题描述】:

我正在尝试将一条信息循环 x 次,但我似乎无法使其与 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:
        ...............

【问题讨论】:

    标签: python loops for-loop range


    【解决方案1】:

    您可以合并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:
            ...
    

    【讨论】:

      【解决方案2】:

      这将基于最短迭代器迭代n 次。

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

      【讨论】:

        【解决方案3】:

        只需创建一个迭代器。

        import itertools
        
        it = itertools.repeat(x.findChildren("section", recursive=False), times=n)
        
        for child in it:
            #do your job
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-30
          • 2016-01-09
          • 1970-01-01
          相关资源
          最近更新 更多