【问题标题】:How do I get the social media usernames using request queries?如何使用请求查询获取社交媒体用户名?
【发布时间】:2021-10-31 11:12:01
【问题描述】:

我正在尝试使用 python 的请求库从this 个人资料接收社交媒体,但我似乎无法使其工作 这是我的尝试之一:

import requests
def get_user():
    url = "https://hasura2.foundation.app/v1/graphql"

    headers = {
        "user-agent": "Mozilla/5.0"
    }

    query = """
        query hasuraUserProfileByPublicKey($publicKey: String!) {
            user: user_by_pk(publicKey: $publicKey) {
        ...HasuraUserFragment
        }
    }

    fragment HasuraUserFragment on user {
        instaSocialVerifs {
                0 {
                    username
                }
        }
        twitSocialVerifs {
                0 {
                    username
                }
        }
        links
    }
"""

payload = {
    "operationName": "hasuraUserProfileByPublicKey",
    "query": query,
    "variables": {
        "publicKey": "0xF9D6fcE6Cce28c0Cd62c5CAf045f4F6233888989"
    }
}

response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()

return response.json()["data"]["user"]

我收到了错误:

    return response.json()["data"]["user"]
    KeyError: 'data'

我对网络抓取还很陌生,如果有任何帮助,我将不胜感激!

【问题讨论】:

    标签: python web-scraping python-requests


    【解决方案1】:

    我将解释错误以及您以后应该如何处理字典 当您使用 response.json()["data"]["user] 时,如果 response.json 没有数据键,您将收到此错误。我的建议是首先看看response.json() 打印这个,看看它返回什么样的数据,然后我建议你使用像这样response.json().get("data", {}).get("user","") 这样的符号即使你没有得到这些键也不会给出错误响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 2020-11-07
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多