【问题标题】:Difficulties with JSON using Python's requests library使用 Python 的 requests 库处理 JSON 的困难
【发布时间】:2020-11-20 14:08:26
【问题描述】:

在尝试抓取 producthunt 时,

import requests

headers = {
    'authority': 'www.producthunt.com',
    'pragma': 'no-cache',
    'cache-control': 'no-cache',
    'upgrade-insecure-requests': '1',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'none',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    'accept-language': 'en-US,en;q=0.9',
}

response = requests.get('https://www.producthunt.com/', headers=headers)

我发现返回的响应没有要转换为 json 的有效字符串。在尝试用 response.text.replace() 替换引号类型并用 json.loads(re.sub(r'^jsonp\d+(|)\s+$', '', response.text 返回json )),我仍然得到同样的错误。

错误:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

想法?

【问题讨论】:

  • 将标题更改为'Accept':'application/json' 可能会有所帮助。
  • ^ 您接受 XHTML 或图像作为响应
  • 另请注意:producthunt.com 本身就是 HTML...没有什么神奇的方法可以将任何网页转换为 JSON
  • 很遗憾没有,我已经试过了:(
  • 向我们展示完整的错误回溯和引发错误的完整代码。还向我们展示返回的状态码和响应正文的开头。

标签: python json python-requests


【解决方案1】:

问题与 JSON 无关

您请求的是网页,而不是 JSON API

$ curl -sH 'Accept: application/json' https://www.producthunt.com/ | head -c 200
<!DOCTYPE html><html lang="en"><head><title>Product Hunt – The best new products in tech.</title><link rel="canonical" href="https://www.producthunt.com/"/><meta name="description" content="Product %

您应该使用 beautifulsoup 或 selenium-webdriver 来提取 HTML 内容,然后解析为 JSON,具体取决于您的需要


实际上,该网站使用 GraphQL https://www.producthunt.com/frontend/graphql

【讨论】:

  • hm,所以稍微让我失望的是 data = '${"operationName":"HomePage","variables":{"cursor":"NQ==","featured":true,"includePromotedPost":false,"visibleOnHomepage":true,"includeLayout":false},"query":"query HomePage($cursor: String, $postCursor: String, $featured: Boolean\\u0021, $includePromotedPost: Boolean\\u0021, $visibleOnHomepage: Boolean\\u0021)}' response = requests.get('https://www.producthunt.com/frontend/graphql', headers=headers, data =data) 与原始标题只是给我一个错误``` {'status': 400, 'error': 'Bad Request'} ` ``
  • 不确定,因为我不管理 ProductHunt。我建议在 python 中使用 GraphQL 库而不是请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 2013-08-15
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多