我試圖用POST請求啓動一個Selenium測試到我的應用程序。有什麼辦法可以使用Selenium開始POST請求嗎?
而不是一個簡單的open(/startpoint)
我想這樣做open(/startpoint, stuff=foo,stuff2=bar)
有沒有辦法做到這一點?
我問這是因爲原來的網頁,其中職位,這個起點取決於經常離線(開發環境),外部供應商,因此往往會失敗爲時尚早(並且不是測試的主題)
我想發送數據爲GET也可以。我只想使用POST方法。
我試圖用POST請求啓動一個Selenium測試到我的應用程序。有什麼辦法可以使用Selenium開始POST請求嗎?
而不是一個簡單的open(/startpoint)
我想這樣做open(/startpoint, stuff=foo,stuff2=bar)
有沒有辦法做到這一點?
我問這是因爲原來的網頁,其中職位,這個起點取決於經常離線(開發環境),外部供應商,因此往往會失敗爲時尚早(並且不是測試的主題)
我想發送數據爲GET也可以。我只想使用POST方法。
簡短的回答:
不可以,但你也許能有點filthing的做到這一點。如果您打開一個測試頁面(使用GET),然後評估該頁面上的一些JavaScript,您應該能夠複製POST請求。請參閱JavaScript post request like a form submit以瞭解如何使用JavaScript複製POST請求。
希望這會有所幫助。
硒IDE讓你運行JavaScript使用storeEval命令。如果你有測試頁面(HTML,而不是XML),並且你只需要執行POST請求,上面提到的解決方案工作正常。
如果您需要POST/PUT/DELETE或任何其他的要求,那麼你就需要另一種方法:
的XMLHttpRequest!
下面列出的例子已經過測試 - 所有方法(POST/PUT/DELETE)都可以正常工作。
<!--variables-->
<tr>
<td>store</td>
<td>/your/target/script.php</td>
<td>targetUrl</td>
</tr>
<tr>
<td>store</td>
<td>user=user1&password</td>
<td>requestParams</td>
</tr>
<tr>
<td>store</td>
<td>POST</td>
<td>requestMethod</td>
</tr>
<!--scenario-->
<tr>
<td>storeEval</td>
<td>window.location.host</td>
<td>host</td>
</tr>
<tr>
<td>store</td>
<td>http://${host}</td>
<td>baseUrl</td>
</tr>
<tr>
<td>store</td>
<td>${baseUrl}${targetUrl}</td>
<td>absoluteUrl</td>
</tr>
<tr>
<td>store</td>
<td>${absoluteUrl}?${requestParams}</td>
<td>requestUrl</td>
</tr>
<tr>
<td>storeEval</td>
<td>var method=storedVars['requestMethod']; var url = storedVars['requestUrl']; loadXMLDoc(url, method); function loadXMLDoc(url, method) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4) { if(xmlhttp.status==200) { alert("Results = " + xmlhttp.responseText);} else { alert("Error!"+ xmlhttp.responseText); }}}; xmlhttp.open(method,url,true); xmlhttp.send(); }</td>
<td></td>
</tr>
澄清:
$ {requestParams} - 你想發佈的參數(如參數1 =值1 &參數2 =值3 &參數1 =值3) ,因爲你需要,你可以指定許多參數
$ {targetUrl這個} - 路徑腳本(如果您有位於http://domain.com/application/update.php一頁,然後targetUrl這個應該等於/application/update.php)
$ {requestMethod} - 方法類型(在這種特定情況下它應該是「POST」,但可以「PUT」或「刪除」或任何其他)
硒目前不提供的API這,但有幾種方法可以在您的測試中啓動HTTP請求。這取決於你在寫什麼語言。
在Java爲例,它可能是這樣的:
// setup the request
String request = "startpoint?stuff1=foo&stuff2=bar";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// get a response - maybe "success" or "true", XML or JSON etc.
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
response.append('\r');
}
bufferedReader.close();
// continue with test
if (response.toString().equals("expected response"){
// do selenium
}
一個非常實用的方式做,這是創建你的測試的虛擬起始頁面,僅僅是用POST形式,具有單「開始測試」按鈕和一堆<input type="hidden"
...元素與適當的發佈數據。
例如,你可以創建一個SeleniumTestStart.html
頁面,內容如下:
<body>
<form action="/index.php" method="post">
<input id="starttestbutton" type="submit" value="starttest"/>
<input type="hidden" name="stageid" value="stage-you-need-your-test-to-start-at"/>
</form>
</body>
在這個例子中,index.php的是你正常的Web應用程序的位置。然後
在您的測試開始時的硒代碼將包括:
open /SeleniumTestStart.html
clickAndWait starttestbutton
這非常類似於自動測試使用的其他模擬和存根技術。你只是嘲笑Web應用程序的入口點。
很顯然,在這種方法的一些侷限性:
請考慮閱讀我的文章左右在Qualities of an Ideal Test
如果您正在使用Python selenium
綁定,如今,有一個擴展selenium
- selenium-requests
:
擴展硒類的webdriver從Reques包括請求功能 ts庫,同時做所有需要的cookie和 請求頭處理。
例子:
from seleniumrequests import Firefox
webdriver = Firefox()
response = webdriver.request('POST', 'url here', data={"param1": "value1"})
print(response)
這看起來很有希望,但有一些問題,首先是如果我使用'webdriver.request',它會打開一個新選項卡而不是現有的選項卡,並在請求結束時關閉,其次它不會呈現預期的頁面。例如:假設我發送GET請求'webdriver.request('GET','http://example.com/some/path',data = {'a':1,'b'= 2}',瀏覽器打開並只顯示'http:// example.com /'而不是'http://example.com/some/path?a = 1&b = 2' – bawejakunal 2016-04-22 05:23:48
@bawejakunal但是如何發佈請求? – Volatil3 2016-08-17 10:48:22
好吧,我同意@Mishkin Berteig - 敏捷教練的回答。使用表單是使用POST功能的快速方法。
無論如何,我看到一些關於JavaScript的提及,但沒有代碼。我已經爲我自己的需要,其中包括jQuery易於POST和其他人。
基本上,使用driver.execute_script()
您可以發送任何JavaScript,包括Ajax查詢。
#/usr/local/env/python
# -*- coding: utf8 -*-
# proxy is used to inspect data involved on the request without so much code.
# using a basic http written in python. u can found it there: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/
import selenium
from selenium import webdriver
import requests
from selenium.webdriver.common.proxy import Proxy, ProxyType
jquery = open("jquery.min.js", "r").read()
#print jquery
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "127.0.0.1:3128"
proxy.socks_proxy = "127.0.0.1:3128"
proxy.ssl_proxy = "127.0.0.1:3128"
capabilities = webdriver.DesiredCapabilities.PHANTOMJS
proxy.add_to_capabilities(capabilities)
driver = webdriver.PhantomJS(desired_capabilities=capabilities)
driver.get("http://httpbin.org")
driver.execute_script(jquery) # ensure we have jquery
ajax_query = '''
$.post("post", {
"a" : "%s",
"b" : "%s"
});
''' % (1,2)
ajax_query = ajax_query.replace(" ", "").replace("\n", "")
print ajax_query
result = driver.execute_script("return " + ajax_query)
#print result
#print driver.page_source
driver.close()
# this retuns that from the proxy, and is OK
'''
POST http://httpbin.org/post HTTP/1.1
Accept: */*
Referer: http://httpbin.org/
Origin: http://httpbin.org
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 7
Cookie: _ga=GAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; _gat=1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,en,*
Host: httpbin.org
None
a=1&b=2 <<---- that is OK, is the data contained into the POST
None
'''
更多的測試比其他答案。 – Smar 2015-03-16 12:00:11