【发布时间】:2021-12-04 00:14:15
【问题描述】:
我有一个 LinkedIn 帖子 ID 列表。我需要通过另一个请求请求每个帖子的共享统计信息。
请求函数如下所示:
def ugcp_stats(headers):
response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List(urn%3Ali%3AugcPost%3A{shid},urn%3Ali%3AugcPost%3A{shid2},...,urn%3Ali%3AugcPost%3A{shidx})', headers = headers)
ugcp_stats = response.json()
return ugcp_stats
urn%3Ali%3AugcPost%3A{shid},urn%3Ali%3AugcPost%3A{shid2},...,urn%3Ali%3AugcPost%3A{shidx} - 这些是共享 urn。它们的数量取决于我列表中的元素数量。
接下来我该怎么做?我是否应该计算列表中的元素数量并以某种方式修改请求 URL 以包含所有元素?或者也许我应该遍历列表并对每个元素发出单独的请求,然后将所有响应附加到一个 json 文件中?
我很挣扎,我不太确定如何写这个。我什至不知道如何将元素解析为请求。虽然我怀疑它可能看起来像这样:
for shid in shids:
def ugcp_stats(headers):
response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List(urn%3Ali%3AugcPost%3A & {shid})', headers = headers)
ugcp_stats = response.json()
return ugcp_stats
更新 - 关注您的分析 现在的代码如下所示:
link = "https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List"
def share_stats(headers, shids):
# Local variable
sample = ""
# Sample the shids in the right pattern
for shid in shids: sample += "urn%3Ali%3AugcPost%3A & {},".format(shid)
# Get the execution of the string content
response = eval(f"requests.get('{link}({sample[:-1]})', headers = {headers})")
# Return the stats
return response.json()
if __name__ == '__main__':
credentials = 'credentials.json'
access_token = auth(credentials) # Authenticate the API
headers = headers(access_token) # Make the headers to attach to the API call.
share_stats = share_stats(headers) # Get shares
print(share_stats)
但似乎什么都没有发生。它完成了脚本,但我什么也没得到。怎么了?
【问题讨论】:
-
如果您确实发现需要为此用例发出多个 API 请求,我建议使用
concurrent.futures.ThreadPoolExecutor并且可能使用它的“地图”函数 IIRC提供 - 感觉它很适合这个工作流程。 -
您可以使用 exec 或 eval。他们做同样的事情,两者都会从字符串中执行 python 代码。因此会将您的消息解释为 python 代码。他们之间的区别正在回归。 eval 也将返回执行的值,而 exec 将只执行而不返回值(如果它)。这将帮助您自动化链接字符串类型中的“shid”提要。还可以考虑将@rv.kvetch 建议作为一种优化策略,以便从现在开始利用多线程技术。
标签: python python-3.x linkedin-api