呦吼吼吼 发表于 2020-4-8 20:20:55

求助

作为一名python的初学者,学习目的主要是应付自己的毕业设计,当让也是希望自己可以再学一门编程语言。再毕设中需要用到爬虫,在程序变成运行的过程中,我的循环编码是这样的
if __name__ == '__main__':
    for yearin range(2011, 2021):
      for month in range(1, 13):
            if month >= 10 andyear >= 2017:
                url = "http://tianqi.2345.com/t/wea_history/js/" + str(year) + str(month) + "/58606_" + str(year) + str(
                  month) + ".js"

            else:
                url = "http://tianqi.2345.com/t/wea_history/js/58606_" + str(year) + str(month) + ".js"我设计这个程序本意是想2017年10月之前使用http://tianqi.2345.com/t/wea_history/js/58606_" + str(year) + str(month) + ".js"这个网址的,2017年10月之后转而从"http://tianqi.2345.com/t/wea_history/js/" + str(year) + str(month) + "/58606_" + str(year) + str(                  month) + ".js"这个链接中爬取其他的数据。但运行下来发现结果是2017年之后的每年10月到12月才会使用那个较长的链接。也就是那个年份和月份并不会像我印象中十进制里十位数和个位数的关系,而是就像是并列的两个循环。但我又一时不知道改这个程序,所以在其次求助,希望把循环改成2017年10月前后从两个链接中获取数据。

suchocolate 发表于 2020-4-8 22:58:15

if (month >= 10 andyear >= 2017) or (year > 2017):

疾风怪盗 发表于 2020-4-9 12:02:38

多用几个if判断行否
if year >= 2017:
    if year == 2017 and month >= 10:
                url = "http://tianqi.2345.com/t/wea_history/js/" + str(year) + str(month) + "/58606_" + str(year) + str(month) + ".js"
    elif year >= 2018 :
                url = "http://tianqi.2345.com/t/wea_history/js/" + str(year) + str(month) + "/58606_" + str(year) + str(month) + ".js"
    else:
                url = "http://tianqi.2345.com/t/wea_history/js/58606_" + str(year) + str(month) + ".js"
else:
                url = "http://tianqi.2345.com/t/wea_history/js/58606_" + str(year) + str(month) + ".js"

疾风怪盗 发表于 2020-4-9 12:06:25

或者要写得简单点,可以用datetime模块,格式化年月日,直接用2017年10月做比较,大于这个日期的用长的地址,代码量会少点
页: [1]
查看完整版本: 求助