1

在这里,我创建了一个我想通过函数运行的网站列表。

import requests

item_ids=[11732, 536]
url_template = 'http://www.grandexchangecentral.com/include/gecgraphjson.php?jsid=%r'
your_sites = []

for i in range(0, len(item_ids)):
    result = url_template % item_ids[i]
    your_sites.append(result)

棘手的部分(无论如何对我来说)是创建一个函数,该函数将每个项目放入your_sites并通过函数对其进行迭代。我考虑过使用某种 for 循环,但我不确定如何实现它,并认为无论如何可能有更有效的方法。这是我的尝试,它返回TypeError: 'NoneType' object is not iterable.

def data_grabber(): 
    for i in range(0, len(your_sites)): 
        url = your_sites[i]
        r = requests.get(url, headers={'Referer': 'www.grandexchangecentral.com'})
        data = r.json
        prices = [i[1] for i in data]

我希望它prices为每个网站返回,但我的努力只能得到错误和 None 值。任何帮助将非常感激。

4

1 回答 1

1

不要创建your_sites全局变量,将它作为参数传递真的很容易。您不需要for循环的显式索引,只需迭代您感兴趣的对象。当您确实需要显式索引时,请使用enumerate()

def data_grabber(your_sites): 
    for url in your_sites: 
        r = requests.get(url, headers={'Referer': 'www.grandexchangecentral.com'})
        data = r.json   # if r.json None the next line will fail
        prices = [i[1] for i in data]

如果没有,不确定你想做什么r.json。你可以试试这样的

        data = r.json or []
于 2012-11-01T00:14:44.340 回答