简体   繁体   English

嵌套 for 循环以创建 url 列表

[英]Nested for loop to create list of urls

I am looking for a way to create a list of urls by modifying the name of the country and the date/time.我正在寻找一种通过修改国家名称和日期/时间来创建 url 列表的方法。

For each country, each day and each hour of the day I need to create a unique url.对于每个国家/地区、每天和每天的每个小时,我都需要创建一个唯一的 url。


import datetime

start_date = datetime.date(2019, 4, 4)
end_date = datetime.date(2019, 4, 5)
delta = datetime.timedelta(days=1)

list_of_urls = []

list_of_countries = ['france', 'germany', 'spain']


for country in list_of_countries:
    while start_date <= end_date:
        for hour in range(0, 24, 1):
            base_url = 'https://thewebsite.com/'+ country +'/'+ start_date.strftime("%Y-%m-%d")
            url = base_url + '/' + str(hour) + '/'
            list_of_urls.append(url)
        start_date += delta 

print(list_of_urls)

It must be very basic but I don't understand why the for loop is applying only to the first country and not the three of them.它一定是非常基本的,但我不明白为什么 for 循环只适用于第一个国家而不适用于其中三个国家。 When printing list_of_urls , only france appears (each day from 0 to 24hours)...打印list_of_urls时,只出现法国(每天从 0 到 24 小时)...

Any help would be greatly appreciated.任何帮助将不胜感激。

Thank you,谢谢,

You need to reset the start date each time through the for loop.每次通过 for 循环都需要重新设置开始日期。 Here is the fixed script:这是固定的脚本:

import datetime

start_date = datetime.date(2019, 4, 4)
end_date = datetime.date(2019, 4, 5)
delta = datetime.timedelta(days=1)

list_of_urls = []
list_of_countries = ['france', 'germany', 'spain']

for country in list_of_countries:
    current_date = start_date

    while current_date <= end_date:
        for hour in range(0, 24, 1):
            base_url = 'https://thewebsite.com/'+ country +'/'+ current_date.strftime("%Y-%m-%d")
            url = base_url + '/' + str(hour) + '/'
            list_of_urls.append(url)
        current_date += delta 

print(list_of_urls)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM