Python selenium close modal window after reading its content - selenium

I have the HTML as following:
function showModal(msg) {
var content = document.getElementById("modal-content");
content.innerHTML = msg;
modal.style.display = "block";
}
showModal(msg + "<br>Job started, check status on the project jobs page.");
After all is said and done, I get the following window:
How do I read the content of the box and if there is "Success" I can click the close on top right to go back to the previous page.
I don't have a clue how to approach this.
Edit: Extended HTML looks as following:
function makeInputScenario(ids,params,has_extra = false) {
var sd = gete("sdate").value;
var ed = gete("edate").value;
var sdt = new Date(sd);
var edt = new Date(ed);
if (sdt > edt) {
showModal("Start date is after end date, please fix!");
return;
}
var p = gete("pool").value;
var dzr = gete("dzr").value;
var pfd = gete("pfd").value;
var udb = gete("udb").value;
var uds = gete("uds").value;
if (uds == "None") uds = "";
var rop = gete("rop-text").value;
var fuds = gete("fuds").value;
if (fuds == "None") fuds = "";
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() {
hideProgress();
if (!params) setInteraction(false);
if (xhr.status == 200) {
var msg = "<strong>SUCCESS:</strong><br><pre>" + xhr.responseText + "</pre>"
showModal(msg);
if (params) {
if (has_extra) {
showProgress("Processing, please wait...");
doAction("run-params","POST","/scenario/run","user=PJMRTO LONG RUN AUCTION" + params + "&cir=" + getCir(),function (ret) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<p>" + ret + "</p>");
});
} else {
var ods = gete("ods").value;
showProgress("Adding new job, please wait...");
doAction("run-params","POST","/job","user=PJMRTO LONG RUN AUCTION&sdate=" + sd + "&edate=" + ed + "&ids=" + ids + "&ods=" + ods + "&rops=" + encode(rop) + "&post=" + encode("") + "&std=" + encode("") + "&cir=" + getCir(),function (job) {
showProgress("Starting job " + job + ", please wait...");
doAction("run-params","POST","/run","id=" + job + params,function (x) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<br>Job started, check status on the project jobs page.");
});
});
}
}
} else if (xhr.status == 500) {
setInteraction(false);
clearTimeout(updProgrs);
var logurl = "/idblog?q=host&name=" + encode(ids) + "&pool=" + encode(p) + "&sd=" + encode(sd) + "&ed=" + encode(ed);
showModal(wrapError("<pre>" + xhr.responseText + "</pre><br><button onclick=\"getIDBlog('" + logurl + "');\" class=\"btn btn-primary\">Download Log</button>"));
}
},false);
setInteraction(true);
if (params) {
gete("start-job").style.display = "none";
gete("host-status").style.display = "none";
}
var sparams = "user=PJMRTO LONG RUN AUCTION&pool=" + p + "&dzr=" + dzr + "&pfd=" + pfd + "&ids=" + ids + "&sdate=" + sd + "&edate=" + ed + "&udb=" + udb + "&uds=" + uds + "&rop=" + encode(rop);
if (fuds != "") {
sparams += "&fuds=" + fuds + "&ius=" + gete("ods").value;
showProgress("Creating base and fixed UC input scenarios, please wait...");
} else {
showProgress("Creating input scenario, please wait...");
}
updProgrs = setTimeout(updateProgress, 300000);
xhr.open("POST","/scenario",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("x-csrf-token","NhISQUB1eCANGh46HwsgTnsAISkCAAAATeFn4B0myInXzZc7+8QJMA==");
xhr.send(sparams);
}

So here variable "msg" is storing the value "SUCCESS". It would be better to get the variable "msg" usin javascript.
So that would be :-
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://Reachyourpage")
message = driver.execute_script("return msg")
print ("SUCCESS" in message)
It should return true in case of success. I am no expert in Python but just a beginner so mind my coding.. !!
C# equivalant here would be :-
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
string title = js.ExecuteScript("return msg");
Here, title will have the complete message.
The algorithm is to get the value of "msg" var using javascript.
For Closing the message, have u tried using SendKeys(Keys.Esc) ??
Hope it Helps!!

Related

using google app script to make spreadsheet into a pdf but getting html

I created a new spreadsheet with a single sheet holding the subset of data of interest. My script is in the original spreadsheet. In that code I am attempting to create a PDF of the new spreadsheet. The URL that my code generates is:
exportUrl=https://docs.google.com/spreadsheets/d/1M82johI78eIrEf8u9RV_5kPgCDAaSfOcoGVYAyno5gE/?usp=drivesdk/export?exportFormat=pdf&format=pdf&size=LETTER&portrait=true&fitw=true&top_margin=0.75&bottom_margin=0.75&left_margin=0.7&right_margin=0.7&sheetnames=false&printtitle=false&pagenum=false&gridlines=true&fzr=FALSE
The PDF generated in MyDrive does not have the icon of a PDF. If I preview it I see:
<!DOCTYPE html><html lang="en"><head><script nonce="siOEWKm8X/lqnbWRNS06ow">var DOCS_timing={}; DOCS_timing['pls']=new Date().getTime();</script><meta property="og:title" content="tempSs"><meta property="og:type" content="article"><meta property="og:site_name" content="Google Docs"><meta property="og:url" content="https://docs.google.com/spreadsheets/d/1M82johI78eIrEf8u9RV_5kPgCDAaSfOcoGVYAyno5gE/edit?usp=drivesdk/export?exportFormat%3Dpdf&format=pdf&size=LETTER&portrait=true&fitw=true&top_margin=0.75&bottom_margin=0.75&left_margin=0.7&right_margin=0.7&sheetnames=false&printtitle=false&pagenum=false&gridlines=true&fzr=FALSE&usp=embed_facebook"><meta property="og:description" content="Sheet1
Abdalla,WilliamAbdalla
Aden,VickieAden
Allen,VeronicaAllen
etc.
When I download it and it has a file extension of html. If I open it the data is there but there is a lot of header stuff which makes no sense. If I change the file extension to pdf I get Error: Failed to load pdf
My code:
/**
* based on https://xfanatical.com/blog/print-google-sheet-as-pdf-using-apps-script/
*/
function exportAsPDF() {
fileName = “tempSs”;
var ssId = getMostRecentFile(fileName);
var ssBaseUrl = getMostRecentFile(fileName);
var blob = _getAsBlob(ssBaseUrl);
_exportBlob(blob, fileName);
}
/**
* Assume multiple spreadsheets with same name
* only want to use the most recent
*/
function getMostRecentFile(fileName) {
ssIt = DriveApp.getFilesByName(fileName);
var createDate, prevCreateDate, tempSsId;
var result = [];
while (ssIt.hasNext()) {
var file = ssIt.next();
result.push([file.getDateCreated(),file.getId(), file.getUrl()]);
}
var dTime = result.sort()[0][0];
var tempSsId = result.sort()[0][1];
var ssBaseUrl = result.sort()[0][2];
// Logger.log(“tempSsId: ” + tempSsId + ” dTime: ” + dTime);
return ssBaseUrl;
}
function _getAsBlob(ssUrlBase) {
// Logger.log(“ssUrlBase before remove edit: ” + ssUrlBase );
var ssUrlBase = ssUrlBase.replace(/edit?/,”);
Logger.log(“ssUrlBase: ” + ssUrlBase );
var exportUrl = ssUrlBase
+ ‘/export?exportFormat=pdf&format=pdf’
+ ‘&size=LETTER’
+ ‘&portrait=true’
+ ‘&fitw=true’
+ ‘&top_margin=0.75’
+ ‘&bottom_margin=0.75’
+ ‘&left_margin=0.7’
+ ‘&right_margin=0.7’
+ ‘&sheetnames=false&printtitle=false’
+ ‘&pagenum=false’
+ ‘&gridlines=true’
+ ‘&fzr=FALSE’;
Logger.log(‘exportUrl=’ + exportUrl);
var response = UrlFetchApp.fetch(exportUrl, {
headers: {
Authorization: ‘Bearer ‘ + ScriptApp.getOAuthToken(),
},
})
return response.getBlob();
}
Why am I not getting a valid PDF in MyDrive or when downloaded? My thanks to everyone. I would not have got this far without constant use of the fine answers on stackoverflow.
Modification points:
When I saw the URL of exportUrl=https://docs.google.com/spreadsheets/d/1M82johI78eIrEf8u9RV_5kPgCDAaSfOcoGVYAyno5gE/?usp=drivesdk/export?exportFormat=pdf&format=pdf&size=LETTER&portrait=true&fitw=true&top_margin=0.75&bottom_margin=0.75&left_margin=0.7&right_margin=0.7&sheetnames=false&printtitle=false&pagenum=false&gridlines=true&fzr=FALSE. I notice that the modification point.
I think that /?usp=drivesdk/export? is the modification point. Please modify to /export?. I think that this is the reason of your issue.
And, in your script, the fonts of the double quotations and the single quotations are required to be modified. In your script, please modify “ and ” to ", and ‘ and ’ to '.
When above points are reflected to your script, it becomes as follows.
Modified script:
function exportAsPDF() {
fileName = "tempSs";
// var ssId = getMostRecentFile(fileName); // It seems that this variable is not used in your script.
var ssBaseUrl = getMostRecentFile(fileName);
var blob = _getAsBlob(ssBaseUrl);
_exportBlob(blob, fileName);
}
function getMostRecentFile(fileName) {
ssIt = DriveApp.getFilesByName(fileName);
var createDate, prevCreateDate, tempSsId;
var result = [];
while (ssIt.hasNext()) {
var file = ssIt.next();
result.push([file.getDateCreated(),file.getId(), file.getUrl()]);
}
var dTime = result.sort()[0][0];
var tempSsId = result.sort()[0][1];
var ssBaseUrl = result.sort()[0][2];
return ssBaseUrl;
}
function _getAsBlob(ssUrlBase) {
var ssUrlBase = ssUrlBase.replace(/\/edit.+/,""); // Modified
var exportUrl = ssUrlBase
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=LETTER'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.75'
+ '&bottom_margin=0.75'
+ '&left_margin=0.7'
+ '&right_margin=0.7'
+ '&sheetnames=false&printtitle=false'
+ '&pagenum=false'
+ '&gridlines=true'
+ '&fzr=FALSE';
var response = UrlFetchApp.fetch(exportUrl, {headers: {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()}});
return response.getBlob();
}
Note:
From your question, I couldn't understand about _exportBlob(blob, fileName);. So it supposes that _exportBlob(blob, fileName); works.

web3 - event.watch spits out events in random order

I am watching an event:
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
Inside the event I do this tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, ''); Which, long story short, makes a string from the event giving the event from the block (i.e. It gives the event made at block 173).
I then set a <h2> element's text from each event. When this happens it sets them in a seemingly random order. What can be going on, it sets them from block 0 to the latest block, so how can this happen.
Here is the full code: https://pastebin.com/wGt5kL1Y
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
i++;
messages = "";
messages = JSON.stringify(results.args);
if(i === messageToGet) {
if(messages.split(":")[1].split(",")[0] != '""') {
console.log(messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split(",")[0].split("}")[0].split("}")[0] + ")");
tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
} else {
console.log("(No included text)" + "(From: " + messages.split(":")[2].split(",")[0].split("}")[0] + ")");
tempString = (("(no included text) " + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
}
if((messages.split(":")[1].split(",")[0] === undefined) || (messages.split(":")[2].split(")")[0] === undefined)) {
return;
}
if(document.getElementById("Message" + placeToSet) != null) {
document.getElementById("Message" + placeToSet).remove();
if(document.getElementById("hr" + placeToSet) != null) {
document.getElementById("hr" + placeToSet).remove();
}
}
if(document.getElementById("Message" + placeToSet) === null) {
var newh2 = document.createElement('h2');
newh2.setAttribute("id", ("Message" + placeToSet));
var text = document.createTextNode(tempString);
newh2.appendChild(text);
document.body.appendChild(newh2);
var newHR = document.createElement('hr');
newHR.setAttribute("id", ("hr" + placeToSet));
}
}
});

openui5 FileUploader not working

I am trying to upload a file with a simple form. I can choose a file but when I click on "upload" nothing happens.
My FileUploader.view.xml is like:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
width="400px"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
My Contoller.controller.js
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
var ControllerController = Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
oFileUploader.upload();
}
});
return ControllerController;
});
When I run this in the debugger I get an Uncaught TypeError:
Uncaught TypeError: Cannot read property '1' of null
at f.handleUploadComplete (FileUploader.controller.js?eval:11)
at f.a.fireEvent (EventProvider-dbg.js:229)
at f.a.fireEvent (Element-dbg.js:427)
at f.fireUploadComplete (ManagedObjectMetadata-dbg.js:426)
at HTMLIFrameElement.eval (FileUploader.js?eval:6)
at HTMLIFrameElement.dispatch (jquery-dbg.js:4737)
at HTMLIFrameElement.c3.handle (jquery-dbg.js:4549)
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
I searched for sample code and it seems my code is ok, but I don't know why I can't upload a file by click on the button.
I solved this problem ! :)
So, instead of using this
var m = /^[(\d\d\d)]:(.)$/.exec(sResponse);
use this in view FileUploader :
sendXHR="true"
After, on controller js you can use for status :
oEvent.getParameter("status")
and for getting answer as a json file :
var jsonfile = JSON.parse(oEvent.getParameter("responseRaw"));
Then access your sent object attributes from server (only when use dataType: 'json')
jsonfile.attribute
I hope this helps a lot!

How do I retrieve the URL of a file hosted on Parse-Server through Javascript?

My code so far:
<script type="text/javascript">
var username = sessionStorage.getItem('username', username);
var password = sessionStorage.getItem('password', password);
var Image = Parse.Object.extend("Image");
var query = new Parse.Query(Image);
query.equalTo("username", username);
query.descending("createdAt");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " images.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
var url = (object.get("image").url);
var createdAt = (object.get("createdAt"));
var image = object.get("image");
alert(url + object.id + createdAt + username + image);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
All variables return the expected values except "image" which returns [Object object] and url which returns function url(){ return this._url;}
in order to get the file URL you need to do the following :
var image = object.get("image"); // here you have ParseFile
var imageUrl = image.url(); // now you have the file URL

How can i attach a value from Json Data to an Actionlink in mvc4

The data got from Json i used to append to a table as rows.First data of the column needs to come in Link format.So i used ActionLink .But i get the following error as "The name 'Transaction_No' does not exist in the current context".
function CreateGrid(result) {
$.ajaxSetup({
cache: false
});
for (i = 0; i < result.data.length; i++) {
debugger;
var chk_row = true;
$('#tbl_RoleMenu tbody').empty().append('<tr id="tr-' + i + '"></tr>');
String Transaction_No = result.data[i].Loan.toString();
$('#tr-' + i).append('<td id="tdLoan-' + i + '"> #Html.ActionLink(Transaction_No, "Create", "Portfolio", null, new { #class = "openDialog", data_dialog_id = "emailDialog" }) </td>');
$('#tr-' + i).append('<td id="tdLoan-1' + i + '">' + result.data[i].Loan + '</td>');
}
}
You seem to be completely mixing server side code with client side javascript. Try fixing this mess:
function CreateGrid(result) {
$.ajaxSetup({
cache: false
});
for (i = 0; i < result.data.length; i++) {
debugger;
var chk_row = true;
$('#tbl_RoleMenu tbody').empty().append('<tr id="tr-' + i + '"></tr>');
var transactionNumber = result.data[i].Loan;
$('#tr-' + i).append('<td id="tdLoan-' + i + '">' + transactionNumber + '</td>');
$('#tr-' + i).append('<td id="tdLoan-1' + i + '">' + result.data[i].Loan + '</td>');
}
}
As an alternative to this horrible mess I would recommend you create this markup on your server using a partial view. I guess that you are calling this function after performing an AJAX request to a controller action (that currently returns a JsonResult). Modify this controller action so that instead of returning a JsonResult returns a PartialView and then simply inject this new markup into your DOM.