如何修复 if 语句不适用于请求响应?

How to fix if statement not working with requests response?

所以我有一个不和谐的机器人,我试图让它根据请求的响应发送消息

  @commands.command()
    async def ttcheck(self, ctx, msg):
      url = requests.get(f"https://www.tiktok.com/@{msg}")
      print(url)
      if url == "<Response [404]>":
        await ctx.send("Name is not taken go get it!")
      elif url == "<Response [200]>":
        await ctx.send("Name is taken")

我什至有 print(url) 来检查控制台,我收到了 200 和 400 的响应,但由于某种原因,当给出正确的响应时它不会发送消息。有什么线索吗?

除了响应之外,控制台中也没有显示任何内容。

得到returns一个response对象,你需要访问状态码,使用r.status_code,你正在比较一个字符串,因此它没有通过if条件查看。 改成这样,

if r.status_code == 200: ...

几件事:

  • 作为建议,您不应调用 url 来存储 requests.get 中的 return 值的变量,因为它代表请求的响应,而不是 url.
  • 当您执行 print(url) 时,您看到的是响应对象的字符串表示形式,但该对象不是字符串。如果你这样做 print(type(url)) 你会看到它是一个 requests.models.Response,既然是这样,你就不能像你在做的那样与字符串进行比较url == "<Response [404]>".
  • 完成您想要的事情的一种方法是使用响应对象中的 属性 status_code 并构建 response.status_code == 200response.status_code == 400 等条件。这将解决问题,因为您现在的条件没有正确检查响应状态代码。