python - 循环创建 URL
问题描述
我正在尝试使用 for 循环创建 URL 列表。它会打印所有正确的 URL,但不会将它们保存在列表中。最终我想使用urlretrieve
.
for i, j in zip(range(0, 17), range(1, 18)):
if i < 8 or j < 10:
url = "https://Here is a URL/P200{}".format(i) + "-0{}".format(j) + ".xls"
print(url)
if i == 9 and j == 10:
url = "https://Here is a URL/P200{}".format(i) + "-{}".format(j) + ".xls"
print(url)
if i > 9:
if i > 9 or j < 8:
url = "https://Here is a URL/P20{}".format(i) + "-{}".format(j) + ".xls"
print(url)
上述代码的输出是:
https://Here is a URL/P2000-01.xls
https://Here is a URL/P2001-02.xls
https://Here is a URL/P2002-03.xls
https://Here is a URL/P2003-04.xls
https://Here is a URL/P2004-05.xls
https://Here is a URL/P2005-06.xls
https://Here is a URL/P2006-07.xls
https://Here is a URL/P2007-08.xls
https://Here is a URL/P2008-09.xls
https://Here is a URL/P2009-10.xls
https://Here is a URL/P2010-11.xls
https://Here is a URL/P2011-12.xls
https://Here is a URL/P2012-13.xls
https://Here is a URL/P2013-14.xls
https://Here is a URL/P2014-15.xls
https://Here is a URL/P2015-16.xls
https://Here is a URL/P2016-17.xls
但是这个:
url
只给出:
'https://Here is a URL/P2016-17.xls'
如何获取所有 URL,而不仅仅是最后一个?
解决方案
有几件事可以显着简化您的代码。首先,这个:
"https://Here is a URL/P200{}".format(i) + "-0{}".format(j) + ".xls"
可以简化为:
"https://Here is a URL/P200{}-0{}.xls".format(i, j)
如果你至少有 Python 3.6,你可以使用f-string代替:
f"https://Here is a URL/P200{i}-0{j}.xls"
其次,Python 有几种方法可以方便地用零填充数字。它甚至可以作为 f 字符串格式的一部分来完成。此外,range
默认情况下从零开始。
所以你的整个原始代码相当于:
for num in range(17):
print(f'https://Here is a URL/P20{num:02}-{num+1:02}.xls')
现在,您要实际使用这些 URL,而不仅仅是将它们打印出来。你提到建立一个列表,可以这样做:
urls = []
for num in range(17):
urls.append(f'https://Here is a URL/P20{num:02}-{num+1:02}.xls')
或使用列表理解:
urls = [f'https://Here is a URL/P20{num:02}-{num+1:02}.xls'
for num in range(17)]
根据您在此处的评论和您的其他问题,您似乎对需要这些 URL 的形式感到困惑。这样的字符串已经是您所需要的。urlretrieve
接受 URL作为 string,因此您不需要做任何进一步的处理。请参阅文档中的示例:
local_filename, headers = urllib.request.urlretrieve('http://python.org/') html = open(local_filename) html.close()
urlretrieve
但是,出于两个原因,我建议不要使用。
正如文档中提到的,
urlretrieve
是一种可能会被弃用的遗留方法。如果您要使用urllib
,请改用该urlopen
方法。但是,正如 Paul Becotte 在回答您的其他问题时提到的那样:如果您要获取 URL,我建议您安装和使用Requests而不是
urllib
. 它更加用户友好。
无论您选择哪种方法,字符串都很好。下面是使用 Requests 将每个指定的电子表格下载到当前目录的代码:
import requests
base_url = 'https://Here is a URL/'
for num in range(17):
filename = f'P20{num:02}-{num+1:02}.xls'
xls = requests.get(base_url + filename)
with open(filename, 'wb') as f:
f.write(xls.content)
推荐阅读
- azure-service-fabric - 从 javascript 调用部署在服务结构上的 web api 时出现选择证书弹出窗口
- mysql - MYSQL 错误 1292 Incorrext datetime value while insert into table
- python - 将 python3.7 升级到 python3.8 后 pipenv、jupyter 和可能的其他命令停止工作
- elasticsearch - 如何从弹性搜索中克隆现有索引数据
- string - 如何将primitive.M转换为映射[字符串]字符串然后转换为字符串?
- android - 升级到 androidx.appcompat:appcompat:1.2.0 问题
- python - Numpy.array 索引
- flutter - 如何在颤动的单个列表中获取多个项目?
- python - 我正在尝试创建一个情节性的旭日形图,但收到错误消息:'dtype:object,'is not a leaf。'
- identityserver4 - 面临 OpenIdConnectProtocolException : Invalid_Token 错误