代码之家  ›  专栏  ›  技术社区  ›  jjyoh

在python中每x秒运行一次循环,以刮取网站[重复]

  •  0
  • jjyoh  · 技术社区  · 7 年前

    我正在抓取一个网站,当我运行脚本时,它会使API请求崩溃。我想在每次迭代之间中断3秒来迭代循环。

    def printit():
        country_list_id = ['a', 'b', 'c']
        product_list_id = ['1', '2', '3']
    
        for c in country_list_id:
           for p in product_list_id:
              url = "https://www.example.com/api/country_id=" + c + "&product_id=" + p + "&option="
            test(url)
    
    def test(url_final):
            get_url = requests.get(url_final)
            get_text = get_url.text
            print(get_text)
            #I'd like to make a small break here before it iterate again
    
    
    printit()
    
    2 回复  |  直到 4 年前
        1
  •  2
  •   Cyzanfar    7 年前

    使用 time 模块:

    import time
    
         def printit():
            country_list_id = ['a', 'b', 'c']
            product_list_id = ['1', '2', '3']
    
            for c in country_list_id:
               for p in product_list_id:
                  url = "https://www.example.com/api/country_id=" + c + "&product_id=" + p + "&option="
                test(url)
    
        def test(url_final):
                get_url = requests.get(url_final)
                get_text = get_url.text
                print(get_text)
                time.sleep(3)
    
    
        printit()
    
        2
  •  1
  •   Joe Iddon    7 年前

    第一,导入 time :

    import time
    

    然后 sleep 3 :

    time.sleep(3)