python selenium post请求,在Selenium中发出POST请求而不填写表格?

I have an application A that should handle a form submit made with POST method. The actual form, that initiates the request, is in totally separate application B. I am testing application A using Selenium, and I like to write a test case for form submit handling.

How to do this? Can this be done in Selenium at all? Application A does not have a form that can initiate this request.

Note, that the request must use POST, otherwise I could just use WebDriver.get(url) method.

解决方案

With selenium you can execute arbitrary Javascript including programmatically submit a form.

Simplest JS execution with Selenium Java:

if (driver instanceof JavascriptExecutor) {

System.out.println(((JavascriptExecutor) driver).executeScript("prompt('enter text...');"));

}

and with Javascript you can create a POST request, set the required parameters and HTTP headers, and submit it.

var xhr = new XMLHttpRequest();

// false as 3rd argument will forces synchronous processing

xhr.open('POST', 'http://httpbin.org/post', false);

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

xhr.send('login=test&password=test');

alert(xhr.response);

If you need to pass over to selenium the response text then instead of alert(this.responseText) use return this.responseText or return this.response and assign the result of execute_script (python) (executeScript() for java) to a variable.

Here is a full example for python:

from selenium import webdriver

driver = webdriver.Chrome()

js = '''var xhr = new XMLHttpRequest();

xhr.open('POST', 'http://httpbin.org/post', false);

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

xhr.send('login=test&password=test');

return xhr.response;'''

result = driver.execute_script(js);

result will contain the return value of your JavaScript provided that the js code is synchronous. Setting false as the third argument to xhr.open(..) forces the request to be synchronous. Setting the 3rd arg to true or omitting it will make the request asynchronous which will require something like xhr.onload = function({alert(this.responseText);}; to handle the result.

NOTE: If you need to pass string arguments to the javascript make sure you always escape them using json.dumps(myString) or otherwise your js will break when the string contains single or double quotes or other tricky characters.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值