利用Python调用pastebin.com API自动创建paste

在上一篇文章中,已经实现了模拟pastebin.com的账号登录,并且获取了api_dev_key,这一篇文章主要讲一下调用API创建paste

登录之后,进入API页面,发现网站已经提供了几个API接口供调用

 

 在创建paste之前,需要创建一个api_user_key,将得到的api_user_key作为创建paste API的提交数据。

这里给出实现整个任务的代码:

import requests
from lxml import etree

class PasteBin(object):
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def login(self):
        login_url = "https://pastebin.com/login"
        self.session = requests.Session()
        form_data = {
            "submit_hidden": "submit_hidden",
            "user_name": self.username,
            "user_password": self.password,
            "submit": "Login"
        }
        headers = {"content-type": "application/x-www-form-urlencoded"}
        res = self.session.post(login_url, data=form_data, headers=headers)
        if res.status_code != 200:
            raise Exception("login fail")
        # 获取api_dev_key
        self.api_dev_key = self.get_api_dev_key()

    def get_api_dev_key(self):
        api_url = "https://pastebin.com/api"
        text = self.session.get(api_url).content.decode("utf-8")
        html = etree.HTML(text)
        target_divs = html.xpath('//*[@id="content_left"]/div[9]/div/text()')
        if target_divs:
            api_dev_key = target_divs[0]
            print("api_dev_key:", api_dev_key)
        else:
            raise Exception("cannot find api_dev_key")
        return api_dev_key

    def get_api_user_key(self):
        url = "https://pastebin.com/api/api_login.php"
        post_data = {
            "api_dev_key": self.api_dev_key,
            "api_user_name": self.username,
            "api_user_password": self.password
        }
        r = requests.post(url, data=post_data)
        if r.status_code != 200:
            raise Exception("get api_user_key fail")
        return r.text

    def create_paste(self, paste_name, paste_code):
        api_user_key = self.get_api_user_key()
        create_paste_url = "https://pastebin.com/api/api_post.php"
        post_data1 = {"api_dev_key": self.api_dev_key,
                      "api_option": "paste",
                      "api_paste_code": paste_code,
                      "api_paste_name": paste_name,
                      "api_user_key": api_user_key,
                      "api_paste_private": 2}
        r = requests.post(create_paste_url, data=post_data1)
        if r.status_code != 200:
            raise Exception("create paste fail")
        else:
            print("create paste succeed")

if __name__ == "__main__":
    username = "kuang123321"
    password = "xxxxxx"
    p = PasteBin(username, password)
    p.login()
    p.create_paste("by code1", "This is a code test")

 

posted @ 2019-07-12 13:44  ktkt  阅读(867)  评论(0编辑  收藏  举报