1

リクエストで Python を使用しており、リンクを短縮する Web サイトのフォームにデータを送信しようとしています。requests.post を使用したら、短縮リンクへのリンクを変数に保存したいと思います。

ステータス コードについて読んだことがありますが、その使用方法がよくわかりません。入力フォームはこんな感じ。

<form method="post" action="paste.php">
    <div class="row">
        <div class="12u">
            <input type="text" name="name" id="name" placeholder="Name of paste" />
        </div>
    </div>
    <div class="row">
        <div class="12u">
            <textarea name="paste" id="paste" placeholder="Paste contents"></textarea>
        </div>
    </div>
    <div class="row">
        <div class="12u">
            <a type="submit" class="button form-button-submit">Upload</a>
            <a href="#" class="button button-alt form-button-reset">Undo</a>
        </div>
    </div>
</form>

これが私がこれまでに持っているものです。

def create_paste(url):
    title = 'title' # Define your title.
    paste = 'paste' # Define your paste content.

    try:
        durk = requests.post(url, data={'name': title, 'paste': paste})

        if durk.status_code == 302:
            print('Pasted!')
        else:
            print('Not pasted!')
    except:
        raise

どうすればこれを行うことができますか?ありがとう。

編集:リクエストのドキュメントを読み直して問題を解決しました。リダイレクトを許可して r.url を使用すると、貼り付けリンクを表示できます。

def derp():
    title = 'adsfjkl' # Define your title.
    paste = 'asdfasdhfasdflkjashdfkjasht' # Define your paste content.

    r = requests.post('http://website.com/paste.php', data={'name': title, 'paste': paste}, allow_redirects=True)

    if r.status_code == 200:
        print('Pasted! %s' % (r.url))
    else:
        print('Not pasted!')

    print r.url
4

1 に答える 1

3

最も簡単な方法は、実際に Requests.post を使用してから、この投稿結果をbeautifulsoupに渡し、結果を解析することです。

例えば:

import request
from bs4 import BeautifulSoup as BS

response = request.get('http://stackoverflow.com/') 
bs = BS(response.text)

//do some parsing using beautifulsoup to get the link
于 2013-11-01T19:46:24.633 に答える