如何将 while 循环中的变量从硬编码更改为包含 pandas iterrows 循环?

How to change variable in a while loop from hardcoded to incorporate pandas iterrows loop?

我有以下 while 循环来从平台抓取信息:

while result_count != 0:  
   start_at = "startAt=" + str(start_index)
   url = base_url + toget + "&" + start_at + "&" + max_results  
   response = requests.get(url, auth=(username, password))  
   json_response = json.loads(response.text)
   print (json_response)
   page_info = json_response["meta"]["pageInfo"]
   start_index = page_info["startIndex"] + allowed_results  
   result_count = page_info["resultCount"]
   items2 = json_response["data"]
   print(items2)

'toget' 变量是包含不同 ID 的数据框。 我需要 'toget' 变量来遍历 pandas 数据框列的所有元素,每次返回不同的 id,因为这是正确抓取所有信息的唯一方法。

import pandas as pd
toget = {'id': [3396750, 3396753, 3396755, 3396757, 3396759]}

如果您需要循环遍历 pandas DataFrame,建议查看此 post:How to iterate over rows in a DataFrame in Pandas

您问题中的代码声明 toget 一个字典,而不是一个 DataFrame。如果是这样,那么你可以使用下面的代码来循环:

遍历字典

toget = {'id': [3396750, 3396753, 3396755, 3396757, 3396759]}

for i in toget.get('id'):
    print(i)

只需添加 for 循环以遍历您的列表并在 url.

中使用该变量

我要在这里清理的其他一些东西:

  1. 我会为 url 使用 f'{}' 语法,但你的做法很好......只是偏好,因为我认为它更容易阅读
  2. 无需使用 json 包来读取响应。您可以立即执行此操作(请参阅下面的编辑)

我在这里还假设您正在为两个变量 start_indexmax_results 设置一个初始值,因为这段代码一旦进入就会抛出这些变量未定义的错误while 循环。

代码:

import pandas as pd

toget = {'id': [3396750, 3396753, 3396755, 3396757, 3396759]}

for eachId in toget['id']:
    while result_count != 0:  
       start_at = "startAt=" + str(start_index)
       url = url = f'{base_url}{eachId}&{start_at}&{max_results}'  
       response = requests.get(url, auth=(username, password))  
       json_response = json.loads(response.text)
       print (json_response)
       page_info = json_response["meta"]["pageInfo"]
       start_index = page_info["startIndex"] + allowed_results  
       result_count = page_info["resultCount"]
       items2 = json_response["data"]
       print(items2)