所以我一直在尝试Json和一些比较。
所以基本上我有一个Json,其中一些元素包含在一些元素中,而另一些则不包含。
我遇到的问题是,脚本一遍又一遍地继续执行脚本,但由于无法找到将在此Json中找到的元素etc Price,estimatedLaunchDate,因此永远不会执行任何操作
sample = {
"threads": [{
"seoTitle": "used food",
"other_crap": "yeet"
},
{
"seoTitle": "trucks",
"other_crap": "it's a fox!"
"product": {
"imageUrl": "https://imagerandom.jpg",
"price": {
"fullRetailPrice": 412.95
},
"estimatedLaunchDate": "2018-06-02T03:00:00.000",
"publishType ": "DRAW"
},
{
"seoTitle": "rockets",
"other_crap": "i'm rocket man"
},
{
"seoTitle": "helicopter",
"other_crap": "for 007"
"product": {
"imageUrl": "https://imagerandom.jpg",
"price": {
"fullRetailPrice": 109.95
},
"estimatedLaunchDate": "2018-06-19T00:00:00.000",
"publishType": "FLOW"
}
}
]
}
正如你所看到的,在一些json元素中有一些额外的信息,还有我遇到的问题,我该怎么做才能让它继续,或者只是添加etc "Price not found","publishType not found“,而仍然继续json的其余部分?
到目前为止,我已经编写了一段代码来实现这一点:
old_list = []
while True:
try:
resp = requests.get("www.helloworld.com")
new_list = resp.json()['threads']
for item in new_list:
newitemword = item['seoTitle']
if newitemword not in old_list:
try:
print(newitemword) #item name
print(str(item['product']['price']['fullRetailPrice']))
print(item['product']['estimatedLaunchDate'])
print(item['product']['publishType'])
old_list.append(newitemword)
except Exception as e:
print(e)
print("ERROR")
time.sleep(5)
continue
else:
randomtime = random.randint(40, 60)
time.sleep(randomtime)
正如您所看到的,在try except方法中有4个打印,如果其中一个(fullRetailPrice,estimatedLaunchDate,publishType),它将抛出异常,并且不会继续其余的代码,这意味着它将在"seoTitle": "trucks",
元素之后死亡!
发布于 2018-06-28 07:21:40
我不会重写整个示例,但是假设当您查找值时
print(str(item['product']['price']['fullRetailPrice']))
您遵循的一个或多个键可能不在那里。您可以通过执行以下操作在代码中检测到这一点
foo = item.get('product', {}).get('price', {}).get('fullRetailPrice')
if foo:
print(str(foo))
else:
print('Retail price could not be found')
get
的第二个参数是在找不到所需键时返回的值。将此返回设置为空字典{}
将允许您一直检查该行,直到最后。如果找不到任何键,最后一个get
将返回None
。然后,您可以检查foo
是否为None,并相应地打印错误消息。
https://stackoverflow.com/questions/51072596
复制相似问题