使用CSV中的数据对URL进行迭代以获取API数据提取-Python

时间:2018-11-30 22:09:55

标签: python api loops csv iteration

我在一列CSV文件中有大约20,000个邮政编码。我正在尝试通过API根据这些邮政编码提取一些地理选举数据。此API的url朝末尾迭代(邮政编码在每次迭代中都会更改)。我尝试了许多不同的代码示例,但是它们都不起作用。

编辑:在我现在知道的下面粘贴示例是行不通的-主要是因为我不需要剥离功能。但是,如何获取循环以直接从CSV文件中提取邮政编码?还粘贴我收到的错误消息。


    responses = list()

    with open("testpostal.csv") as f:
        for postal in map(str.strip,f):     
            rrr = requests.get('https://represent.opennorth.ca/postcodes/{}'.format(postal))
            data = json.loads(rrr.text)
            responses.append(data)

    print(responses)


JSONDecodeError                           Traceback (most recent call last)
<ipython-input-182-05e370407e9c> in <module>()
      9     for postal in map(str.strip,f):
     10         rrr = requests.get('https://represent.opennorth.ca/postcodes/{}'.format(postal))
---> 11         data = json.loads(rrr.text)
     12         responses.append(data)
     13 

~/anaconda3/lib/python3.7/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

~/anaconda3/lib/python3.7/json/decoder.py in decode(self, s, _w)
    335 
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

~/anaconda3/lib/python3.7/json/decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

3 个答案:

答案 0 :(得分:0)

Python提供了CSV module,您可以执行以下操作:

import csv,requests
URL = 'https://represent.opennorth.ca/postcodes/%s'
responses = []
with open("testpostal.csv") as csv_file:
   csv_reader = csv.reader(csv_file)
   for row in csv_reader:
       responses.append(requests.get(URL % row[0]).json())

这将跳过处理解析CSV文件的烦恼。如果我使用不带空格的加拿大邮政编码,则上面的代码对我有用。

答案 1 :(得分:0)

包括所得到的错误,这些错误将指引您正确的方向。 对于初学者来说,

map(str.strip, f) 

可能并不意味着什么。

使用剥离功能时,应包括要“剥离”的内容以及要剥离的字符串。 例如,来自this教程:

str = "0000000this is string example....wow!!!0000000";
print str.strip( '0' )

返回:

this is string example....wow!!!

答案 2 :(得分:0)

好的,所以我弄清楚我做错了什么。我只是让python以列表形式读取csv列,然后使用for循环以json格式获取结果。粘贴以下代码,以防对任何人有帮助:

import csv

with open('PC2.csv','r') as f:
    lines = f.read()
    list = lines.split('\n')

postcodes = list #not really necessary but I wanted to preserve specific names
response = []

for postcode in postcodes:
    rr = requests.get('https://represent.opennorth.ca/postcodes/{}'.format(postcode))
    data = json.loads(rr.text)
    response.append(data)



print(response)