【问题标题】:github code search api returns html instead of jsongithub代码搜索api返回html而不是json
【发布时间】:2013-09-04 10:36:18
【问题描述】:

我想通过python从github API获取一些数据:

import requests
headers = {'User-Agent': 'Awesome-Octocat-App', 'Accept': 'application/vnd.github.preview+json'}
link = "https://github.com/search?q=chembl+created:>=2000"
r = requests.get(link, headers=headers)

看起来一切都很顺利:

r.ok
>>> True

所以我希望得到 json 作为响应:

r.json()

但这会引发异常:

JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

不幸的是,我拥有的是 html:

r.content

<!DOCTYPE html>
<html>
  <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# githubog: http://ogp.me/ns/fb/githubog#">
  <meta charset='utf-8'>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
...

此 html 包含我正在寻找的所有存储库,但我需要 json 而不是 html。为什么?

【问题讨论】:

    标签: python api github python-requests github-api


    【解决方案1】:

    您需要使用actual API 来获取 JSON 内容。 http://github.com/search 是常规的 HTML 前端。你可能想search for repositories

    import requests
    
    headers = {'User-Agent': 'Awesome-Octocat-App', 'Accept': 'application/vnd.github.preview+json'}
    link = "https://api.github.com/search/repositories"
    query = {'q': 'chembl created:>=2000'}
    r = requests.get(link, headers=headers, params=query)
    

    这给了我:

    >>> r = requests.get(link, headers=headers, params=query)
    >>> r.ok
    True
    >>> r.json().keys()
    [u'total_count', u'items']
    >>> r.json()['total_count']
    17
    

    【讨论】:

      【解决方案2】:

      您正在使用该网址:

      https://github.com/search?q=chembl+created:&gt;=2000

      您应该使用 URL:

      https://api.github.com/search/repositories?q=chembl+created:&gt;=2000.

      这是文档:

      http://developer.github.com/v3/search/#search-repositories

      【讨论】:

        猜你喜欢
        • 2013-09-02
        • 2017-12-21
        • 1970-01-01
        • 1970-01-01
        • 2017-03-28
        • 2019-03-31
        • 2020-08-12
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多