簡體   English   中英

在python中已經打開的url上發送POST請求

[英]Sending POST request on an already open url in python

基本上我想發送以下表單的 POST 請求。

<form method="post" action="">
449 * 803 - 433 * 406 = <input size=6 type="text" name="answer" />
<input type="submit" name="submitbtn" value="Submit" />
</form>

我基本上想要做的是通讀頁面,找出表格中的方程,計算答案,輸入答案作為參數與 POST 請求一起發送,但不打開頁面的新 URL,作為新方程每次打開頁面時都會出現,因此之前獲得的結果已過時。 最后,我想獲取由於發送 POST 請求而出現的頁面。 我被困在我必須在不打開新 URL 實例的情況下發送 POST 請求的部分。 另外,我很感激有關如何在 POST 請求后再次通讀頁面的幫助。 (調用read()就足夠了嗎?)

我目前擁有的 python 代碼看起來像這樣。

import urllib, urllib2

link = "http://www.websitetoaccess.com"
f = urllib2.urlopen(link)

line = f.readline().strip()
equation = ''
result = ''
file1 = open ('firstPage.html' , 'w')
file2 = open ('FinalPage.html', 'w')

for line in f:
    if 'name="answer"' in line:
        result = getResult(line)
    file1.write(line)

file1.close()

raw_params = {'answer': str(result), 'submit': 'Submit'}
params = urllib.urlencode(raw_params)
request = urllib2.Request(link, params)
page = urllib2.urlopen(request)

file2.write(page.read())
file2.close()

是的,最后一個鏈接真的很有幫助,結果我只需要根據這樣的請求創建一個新會話:

s = requests.session()
res1 = s.get(url)

並將其添加為發布請求之后

res2 = s.post(url, data=post_params)

我相信這實現了存儲來自 get 請求的 cookie 並將它們與 post 請求一起發送的結果,從而保持與之前的 get 請求相同的問題。 非常感謝您對 Loknar 問題的幫助和幫助。

我有點困惑,POST 請求將始終是一個新的單獨請求,所以我不明白您所說的“不打開新的 URL 實例”是什么意思……你有沒有試過看看當你這樣做時會發生什么你想手動在這個腳本中做什么? 就像在 Chrome 中打開開發者控制台一樣,轉到網絡選項卡,將保留登錄切換為開啟,刪除歷史記錄,然后手動執行您想要執行的操作? 然后在python中復制它? 此外,我建議您嘗試使用 requests 模塊,它比使用 urllib 更簡單。 只需pip install requests (和pip install lxml )。

import requests
from lxml import etree

url = 'http://www.websitetoaccess.com'
res1 = requests.get(url)
# do something with res1.content
# you could try parsing the html page with lxml
root = etree.fromstring(res1.content, etree.HTMLParser())
# do something with root, find question and calc answer?
post_params = {'answer': str(42), 'submit': 'Submit'}
res2 = requests.post(url, data=post_params)
# check res2 for success or content?

編輯:

您可能遇到了一些標題問題或 cookie 問題。 您可能會收到一些會話 ID,它使服務器能夠確定您在前一個 GET 請求中收到的問題。 POST 請求是與前一個 GET 請求分開的請求,它不能合並為一個請求。 您應該檢查從之前的 GET 請求收到的標頭和/或嘗試設置會話/cookies 處理(如果使用請求很容易做到,請參閱https://requests.readthedocs.io/en/master/user/advanced/ )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM