首页 > 解决方案 > 如何让我的 Python 脚本转到 URL,下载最新文件

问题描述

我编写了这个 Python 脚本来创建一个表格,其中仅包含来自我们体育俱乐部的运动员在全国排名中的表现。目前我必须下载排名文件,然后重新命名。

#import the writer
import xlwt
#import the reader
import xlrd
#open the rankings spreadsheet
book = xlrd.open_workbook('rankings.xls')
#open the first sheet
first_sheet = book.sheet_by_index(0)
#print the values in the second column of the first sheet
print first_sheet.col_values(1)


#open the spreadsheet
workbook = xlwt.Workbook()
#add a sheet named "Club BFA ranking"
worksheet1 = workbook.add_sheet("Club BFA ranking")
#in cell 0,0 (first cell of the first row) write "Ranking"
worksheet1.write(0, 0, "Ranking")
#in cell 0,1 (second cell of the first row) write "Name"
worksheet1.write(0, 1, "Name")    
#save and create the spreadsheet file
workbook.save("saxons.xls")

name = []
rank = []
for i in range(first_sheet.nrows):
    #print(first_sheet.cell_value(i,3)) 
    if('Saxon' in first_sheet.cell_value(i,3)):  
        name.append(first_sheet.cell_value(i,1))
        rank.append(first_sheet.cell_value(i,8))    
        print('a')
for j in range(len(name)):
    worksheet1.write(j+1,0,rank[j])
    worksheet1.write(j+1,1,name[j])


workbook.save("saxons.xls")

作为下一次迭代,我希望它转到特定的 URL 并下载最新的电子表格以用作rankings.xls

我怎样才能做到这一点?

标签: pythonurlxlsxlrdxlwt

解决方案


您可以使用请求库。例如,

import requests

url = "YOUR_URL" 
downloaded_file = requests.get(url)

with open("YOUR_PATH/rankings.xls", 'wb') as file:  
    file.write(downloaded_file.content)

编辑:你提到你想下载最新版本的文件,你可以使用下面的时间来填写月份和年份。

time.strftime("https://www.britishfencing.com/wp-content/uploads/%Y/%m/ranking_file.xls")

YOUR_URL获取最近一个月的排名。


推荐阅读