2016-11-29 4 views
0
from urllib.request import urlopen 
import time 
import json 
import csv 



csvFile = open("C:/Users/Macy/Desktop/Scripts/test.csv", 'w+', newline='') 
writer = csv.writer(csvFile) 
writer.writerow(('City', 'Name', 'Age','Sex','Race')) 

STAGGER_TIME = 1 # of seconds 
CityList = ('Canton') 


for city in CityList: 
    response = urlopen("https://thecountedapi.com/api/counted/?state=TX&city="+city).read().decode('utf-8') 
    responseJson = json.loads(response) 
    print("--------------") 
    print("City: " + str(responseJson.get("city"))) 
    print("Name: " + str(responseJson.get("name"))) 
    print("Age: " + str(responseJson.get("age"))) 
    print("Sex: " + str(responseJson.get("sex"))) 
    print("Race: " + str(responseJson.get("race"))) 
    writer.writerow((responseJson.get("name"), responseJson.get("age"), responseJson.get("sex"), responseJson.get("race"), responseJson.get("city"))) 
    time.sleep(STAGGER_TIME) 

csvFile.close() 

これは私がPythonで実行しようとしているコードです。このコードを実行しようとするたびに、次のようなエラーが表示されます。AttributeError:PythonでAPIリクエストを実行しようとすると 'list'オブジェクトに属性 'get'がありません

"Traceback (most recent call last): 
    File "C:/Users/Macy/Desktop/Texas A&M/Junior Year/Fall Semester/ISYS 281/shooting.py", line 20, in <module> 
    print("City: " + str(responseJson.get("city"))) 
AttributeError: 'list' object has no attribute 'get' 

ここで私は間違っていますか?私は問題を研究しようとしましたが、私が見つけたすべての情報源が私に混乱しています。

from urllib.request import urlopen 
import time 
import json 
import csv 



csvFile = open("C:/Users/Macy/Desktop/Scripts/test.csv", 'w+', newline='') 
writer = csv.writer(csvFile) 
writer.writerow(('City', 'Name', 'Age','Sex','Race')) 



CityList = ('Canton') 


for city in CityList: 
    response = urlopen("https://thecountedapi.com/api/counted/?state=TX&city="+city).read().decode('utf-8') 
    responseJson = json.loads(response)[0] 
    print("--------------") 
    print("City: " + responseJson.get["city"]) 
    print("Name: " + (responseJson.get["name"]) 
    print("Age: " + (responseJson.get["age"]) 
    print("Sex: " + (responseJson.get["sex"]) 
    print("Race: " + (responseJson.get ["race"]) 
    writer.writerow((responseJson.get["name"], responseJson.get["age"], responseJson.get["sex"], responseJson.get["race"], responseJson.get["city"])) 



csvFile.close() 

これは更新されたコードですが、コードを実行すると無効な構文エラーが発生します。

+0

'json.loads(レスポンス)は'リストです。 –

+0

'responseJson = json.loads(response)'の代わりに 'responseJson = json.loads(response)[0]'を返します。 – Abdou

+0

さて、それは実行されますか?そうでない場合は、実際の回答ではありません。あなたはこの投稿を編集することができます –

答えて

0

まず、これはあなたが望むものではありません。

CityList = ('Canton') # This is just a string, not a list/tuple 

for city in CityList: 
    print(city) 

あなたは['Canton']をしたい出力

C 
a 
n 
t 
o 
n 

。実際のリスト


はその後、あなたのJSONは、これがリストである。この

[ <---- notice the bracket 
    { 
    '__v': 0, 
    '_id': '583ce122f708a72906428d9b', 
    'address': 'Texas Hwy 243 and Texas Hwy 64', 

のように見えます。あなたのコードはあなたが辞書を持っていると仮定しています。

これをループして辞書を取得する必要があります。

cities = ['Canton'] # This is a list 
for city in cities: 
    response = urlopen("https://thecountedapi.com/api/counted/?state=TX&city="+city).read().decode('utf-8') 
    for responseJson in json.loads(response): 
     print("--------------") 
     print("City: " + responseJson["city"]) 

または、最初と唯一の辞書項目を取得します。その後

responseJson = json.loads(response)[0] 
print("--------------") 
print("City: " + responseJson["city"]) 

、あなたにSyntaxError ...

あなたはエンコーディングに問題がある

print("City: " + responseJson.get["city"]) # yours 
print("City: " + responseJson["city"])  # mine 
+0

私はあなたの提案を使用しましたが、現在無効な構文エラーが発生しています。 – mace

+0

どちらの提案ですか? –

+0

あなたの最初のオプションは、それをループすると言います – mace

0

を比較。あなたが持っているコンテンツはユニコード形式です。ですから、私はcsvパッケージの代わりにunicodecsvパッケージを提案します。 あなたがpip install unicodecsv

によってunicodecsvパッケージをインストールすることができますが、このようにそれを実装することができます

import time 
import json 
import unicodecsv 
import requests 

with open("C:/Users/Macy/Desktop/Scripts/test.csv", 'w+') as csvFile: 
    writer = unicodecsv.writer(csvFile) 
    writer.writerow(('City', 'Name', 'Age','Sex','Race')) 

    STAGGER_TIME = 1 # of seconds 
    CityList = ['Canton', 'Canton'] 

    for city in CityList: 
     res = json.loads(requests.get("https://thecountedapi.com/api/counted/?state=TX&city="+city).content)[0] 
     print "--------------" 
     city, name, age, sex, race = res['city'], res['name'], res['age'], res['sex'], res['race'] 
     print city,',',name,',',age,',',sex,',',race 
     writer.writerow((city, name, age, sex, race)) 
     time.sleep(STAGGER_TIME) 

出力:

-------------- 
Canton , Mary Lená Pettiet , 33 , Female , White 
-------------- 
Canton , Mary Lená Pettiet , 33 , Female , White 
関連する問題