Reading a github file using python returns HTML tags

后端 未结 5 1608
情书的邮戳
情书的邮戳 2020-12-18 07:40

I am trying to read a text file saved in github using requests package. Here is the python code I am using:

    import requests
    url = \'https://github.co         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 08:16

    There are some good solutions already, but if you use requests just follow Github's API.

    The endpoint for all content is

    GET /repos/:owner/:repo/contents/:path
    

    But keep in mind that the default behavior of Github's API is to encode the content using base64.

    In your case you would do the following:

    #!/usr/bin/env python3
    import base64
    import requests
    
    
    url = 'https://api.github.com/repos/{user}/{repo_name}/contents/{path_to_file}'
    req = requests.get(url)
    if req.status_code == requests.codes.ok:
        req = req.json()  # the response is a JSON
        # req is now a dict with keys: name, encoding, url, size ...
        # and content. But it is encoded with base64.
        content = base64.decodestring(req['content'])
    else:
        print('Content was not found.')
    

提交回复
热议问题