gpt4 book ai didi

python - 如何迭代 JSON 列表以仅查找我网站的 URL?

转载 作者:太空宇宙 更新时间:2023-11-03 20:15:10 25 4
gpt4 key购买 nike

我正在从我的网站提取 JSON 数据,并且想将我所有帖子的 URL(永久链接)附加到列表中。我尝试使用下面的代码迭代 JSON 文件,但当我尝试 for 循环时,出现 TypeError: 'list' object is not callable 。有人可以帮忙吗?

import urllib.request
import json

get_data_url = "http://www.financialgenomeproject.net/wp-json/wp/v2/posts"
json_get_data_url = urllib.request.urlopen(get_data_url)
resp = json.load(json_get_data_url)

url_list = []
for i in resp('content'):
if i('rendered') == 'href=':
url_list.append(['href='])

print(url_list)

最佳答案

你只需要rendererd键,因为protected是bool类型。然后你可以使用str.index选择要选择字符串的哪一部分。

import urllib.request
import json

get_data_url = "http://www.financialgenomeproject.net/wp-json/wp/v2/posts"
json_get_data_url = urllib.request.urlopen(get_data_url)
resp = json.load(json_get_data_url)
<小时/>
url_list=[]
for my_dict in resp:
for key in my_dict['content']:
if key == 'rendered':
my_dict2=my_dict['content'][key]
idi=my_dict2.index('href="http')+len('href="')
idf=my_dict2.index('/"')+1
url=my_dict2[idi:idf]
url_list.append(url)
print(url)
<小时/>

输出:

http://financialgenomeproject.net/2019/05/31/chapter-25-home-not-asset/
http://financialgenomeproject.net/2017/02/26/chapter-3-benjamin-franklin-first-tax-planner/
http://financialgenomeproject.net/table-of-contents/
http://financialgenomeproject.net/2018/11/30/chapter-22-land-ownership/
http://financialgenomeproject.net/about/
http://financialgenomeproject.net/2017/08/23/financial-genome-project-chapter-7/
http://financialgenomeproject.net/2017/09/24/financial-genome-project-chapter-8/
http://financialgenomeproject.net/2017/09/24/financial-genome-project-chapter-8/
http://financialgenomeproject.net/2016/12/09/financial-genome-project-1/
http://financialgenomeproject.net/2018/04/09/chapter-15-do-you-need-a-budget/

获取url所需时间

%%timeit
url_list=[]
for my_dict in resp:
for key in my_dict['content']:
if key == 'rendered':
my_dict2=my_dict['content'][key]
idi=my_dict2.index('href="http')+len('href="')
idf=my_dict2.index('/"')+1
url=my_dict2[idi:idf]
url_list.append(url)
#27.4 µs ± 159 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

现在可以打印

%%timeit
url_list=[]
for my_dict in resp:
for key in my_dict['content']:
if key == 'rendered':
my_dict2=my_dict['content'][key]
idi=my_dict2.index('href="http')+len('href="')
idf=my_dict2.index('/"')+1
url=my_dict2[idi:idf]
url_list.append(url)
print(url)
#1.42 ms ± 60.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
<小时/>

如您所见,如果包含 print(url),时间会显着增加,因此如果您不需要立即查看,建议对此行进行注释

关于python - 如何迭代 JSON 列表以仅查找我网站的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58495213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com