【问题标题】:Loop Multiple URLs Through the Same API Information通过相同的 API 信息循环多个 URL
【发布时间】:2021-11-18 01:41:48
【问题描述】:

我希望通过相同的 API 密钥和基本 URL 循环 URL 列表,以从其 JSON 输出中提取数据。我似乎无法正确设置循环。

这是我所在的地方:

page_URL = ['https://www.usatoday.com','https://www.capitalone.com']

for url in page_URL:
   API_Key = "xyz"
   baseURL = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url="
   strategy = "mobile"
   response_url = baseURL+page_URL+'&key='+API_Key+'&strategy='+strategy
   response = requests.get(response_url).json()
   url_id = response['originLoadingExperience']['id']
   overall_score = response['lighthouseResult']['categories']['performance']['score']*100
   fcp_score = response['originLoadingExperience']['metrics']['FIRST_CONTENTFUL_PAINT_MS']['percentile']/1000
   fid_score = response['originLoadingExperience']['metrics']['FIRST_INPUT_DELAY_MS']['percentile']
   lcp_score = response['originLoadingExperience']['metrics']['LARGEST_CONTENTFUL_PAINT_MS']['percentile']/1000
   cls_score = response['originLoadingExperience']['metrics']['CUMULATIVE_LAYOUT_SHIFT_SCORE']['percentile']/100

明显的问题是试图将我的page_URL 列表与response_URL 连接起来,这不是一个列表,但我不知道如何更正。

感谢任何解决方案。

【问题讨论】:

  • baseURL+page_URL+'&key='+API_Key+'&strategy='+strategy 应该是 baseURL+url+'&key='+API_Key+'&strategy='+strategy。您想使用循环中定义的url
  • 不要共享 API 密钥
  • @C_Z_ 你是大师。
  • @balderman 非常感谢提醒

标签: python json api loops


【解决方案1】:

你有两个问题。第一个问题由@C_Z_5 的评论解决。第二个问题是,当您为 GET 请求发送查询字符串时,必须对参数名称和值进行编码,以免包含某些字符(例如,'?'、'='、'&'、':'、' /', 等等。)。 page_URL 列表中的 URL 具有此类特殊字符,因此您可以使用 quote_plus 函数对此类值进行编码:

from urllib.parse import quote_plus
...
for url in page_URL:
   ...
   response_url = baseURL+quote_plus(url)+'&key='+API_Key+'&strategy='+strategy
   ... # etc.

请注意,如果您不确定它们的内容是否为“安全。”

如果page_URL 中的任何 URL 包含查询字符串,那将是真正的问题。由于没有人这样做,您可能会在不使用quote_plus 对 URL 进行编码的情况下逃脱。但安全总比后悔好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2015-07-23
    相关资源
    最近更新 更多