如何将Python中的列表值附加到URL

2024-05-06 16:46:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基本的url,我想将列表值附加到它上,这样我就有了一个url列表要抓取。我的列表来自一个json文件,看起来像:

[{u'url': [u'/location/subfile/file1.htm', u'/location/subfile/file2.htm', u'/location/subfile/file3.htm', u'/location/subfile/file4.htm']}]

我的基本URL类似于http://example.com/placeforfiles/

最终,我想要的是一个包含基本URL和列表值的URL集合,如下所示:

^{pr2}$

我可能需要附加数千个列表值,所以我知道我需要循环使用它们并附加它们,但是我还没有找到一个有效的解决方案。我正在尝试:

import json

with open ('returned_items.json') as links:
    data = json.load(links)

base_url = 'http://example.com/placeforfiles/{}'

for i in data:
    url = 'http://example.com/placeforfiles/{}'.format(i)
    print url

它正在返回:

http://example.com/placeforfiles/({u'url': [u'/location/subfile/file1.htm', u'/location/subfile/file2.htm', u'/location/subfile/file3.htm', u'/location/subfile/file4.htm']},)

Tags: comjsonhttpurl列表examplelocationfile1
2条回答

这是因为dict是数组中的第一个元素。 循环应该是for i in data[0]["url"]

#replcace data with below line
data = json.loads(links)

#replace your last loop with below
if data and 'url' in data[0]:
 for i in data[0]['url']:
  url = 'http://example.com/placeforfiles{}'.format(i)
  print(url)

相关问题 更多 >