【问题标题】:How to create paste on rentry.co with python?如何使用 python 在rentry.co 上创建粘贴?
【发布时间】:2022-11-11 09:32:57
【问题描述】:

如何创建对rentry.co 的请求以创建粘贴?

我试图在 Python 中解决这个问题,但得到以下响应:

403 reason: Forbidden ... 

我尝试更改 URL 并添加我的 cookie。

我的代码目前如下所示。

import requests

text = "Hello World!"

data = {"text":text}

r = requests.post("https://rentry.co/api", data=data)


print(f"status code: {r.status_code}")
print(f"reason: {r.reason}") ```

【问题讨论】:

标签: python api


【解决方案1】:

尝试这个

#!/usr/bin/env python3

import http.cookiejar
import sys
import urllib.parse
import urllib.request
from http.cookies import SimpleCookie
from json import loads as json_loads

_headers = {"Referer": 'https://rentry.co'}


class UrllibClient:
    """Simple HTTP Session Client, keeps cookies."""

    def __init__(self):
        self.cookie_jar = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookie_jar))
        urllib.request.install_opener(self.opener)

    def get(self, url, headers={}):
        request = urllib.request.Request(url, headers=headers)
        return self._request(request)

    def post(self, url, data=None, headers={}):
        postdata = urllib.parse.urlencode(data).encode()
        request = urllib.request.Request(url, postdata, headers)
        return self._request(request)

    def _request(self, request):
        response = self.opener.open(request)
        response.status_code = response.getcode()
        response.data = response.read().decode('utf-8')
        return response


def new(url, edit_code, text):
    client, cookie = UrllibClient(), SimpleCookie()

    cookie.load(vars(client.get('https://rentry.co'))['headers']['Set-Cookie'])
    csrftoken = cookie['csrftoken'].value

    payload = {
        'csrfmiddlewaretoken': csrftoken,
        'url': url,
        'edit_code': edit_code,
        'text': text
    }

    return json_loads(client.post('https://rentry.co/api/new', payload, headers=_headers).data)


def get_rentry_link(text):

    url, edit_code = '', ''

    response = new(url, edit_code, text)
    if response['status'] != '200':
        print('error: {}'.format(response['content']))
        try:
            for i in response['errors'].split('.'):
                i and print(i)
            sys.exit(1)
        except:
            sys.exit(1)
    else:
        pastebin_link = response['url']
        print('Url:        {}
Edit code:  {}'.format(response['url'], response['edit_code']))

        return pastebin_link

if __name__ == '__main__':
    
    link_list = ['https://stackoverflow.com/', 'https://www.youtube.com/', 'https://www.google.com/']

    pastebin_link = get_rentry_link('
'.join(map(str, link_list)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2021-02-17
    相关资源
    最近更新 更多