需要使用python在XML和JSON响应中打印特定项

时间:2017-07-05 22:38:18

标签: python json xml

我从google maps api得到回复,我只需要从Json响应和XML响应中获得距离。我很难找到关于如何做到这一点的好例子。我应该使用请求和bs4模块来执行此操作。

当第一个为json运行-j或-x为XML时,程序需要3个参数。

第二个是起源城市和州。示例:田纳西州纳什维尔

第三个是目的地城市或州。示例:Smynra,TN

import requests
from bs4 import BeautifulSoup as bs
import sys
import json

funCall = sys.argv[1]
key = "AIzaSyD6-37WvsoTYvlgXKdquv5TRFFwgARvq4w"

def Xfunction():
    x = 4
def aFunction():
    x = 3

if funCall == "-j":
    origin = sys.argv[2]
    dest = sys.argv[3]

    url = "https://maps.googleapis.com/maps/api/distancematrix/json?
           units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})


elif funCall == "-x":
    origin = sys.argv[2]
    dest = sys.argv[3]

    url = "https://maps.googleapis.com/maps/api/distancematrix/xml?
           units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})


elif funCall == "-a":
    aFunction()

忽略顶部的函数我在if语句中获得响应-j是jason,-x是XML。

如果我使用print(req.content)打印我的jason req后,我得到:

b'{\n   "destination_addresses" : [ "Smyrna, TN, USA" ],\n   "origin_addresses" : [ "Nashville, TN, USA" ],\n   "rows" : [\n      {\n         "elements" : [\n            {\n               "distance" : {\n                  "text" : "24.2 mi",\n                  "value" : 39005\n               },\n               "duration" : {\n                  "text" : "31 mins",\n                  "value" : 1873\n               },\n               "status" : "OK"\n            }\n         ]\n      }\n   ],\n   "status" : "OK"\n}\n'

我只需要距离文本值,我不知道如何从json或xml解析它。

1 个答案:

答案 0 :(得分:0)

像这样阅读JSON:

if funCall == "-j":
    origin = sys.argv[2]
    dest = sys.argv[3]
    url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})
    distance = req.json()['rows'][0]['elements'][0][ 'distance']['text']
    print (distance)

输出

24.2 mi

这样的XML:

elif funCall == "-x":
    origin = sys.argv[2]
    dest = sys.argv[3]
    url = "https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})
    soup = bs(req.text, "xml")
    distance = soup.find('distance').findNext('text').text
    print (distance)

输出

24.2 mi

但是你在if和elif语句中重复了2行(近4行),如果你在代码更好的语句之前移动它们。