Selenium and wordpress: New post test - wordpress

I've been looking a bit at Selenium, and I'm beginning to like it, since I know some Java programming and find both Java and C# pretty straight-forward for simple things like this.
However, I'm struggling with a test that creates a new post in Wordpress, from the Dashboard page:
This is the Selenium code (in C#):
(The Driver instance is, obviously, a driver class I've created - for starting the browser and connecting to the wordpress site.)
1: Driver.Instance.FindElement(By.Id("title)).SendKeys(title);
2: Thread.Sleep(1000);
3:
4: Instance.SwitchTo().Frame("content_ifr");
5: Thread.Sleep(1000);
6:
7: Driver.Instance.SwitchTo().ActiveElement().SendKeys("something");
Now, what happens is that the title is easily found (by ID, so I wouldn't expect problems there), and I can easily insert the title text (line 1).
But the inline frame for the post body is causing problems. When running the test, after the topic is filled in, the cursor changes to the body area (line 4) - as planned. However, nothing more happens. The SendKeys("string") method (ine 7) doesn't seem to work there.
Any ideas?
EDIT: Of course - an important piece of information is that the iframe in Wordpress simply loads a TinyMCE editor. So, in the page source, there's only a body tag with the javascript loading of the editor.
EDIT2: Of course, something suddenly changed. Without ANY change to the wordpress page, the "content_ifr" is now suddenly missing (?!!!!!?) The Selenium test fails with "unable to locate frame...", and it's also suddenly missing from the page source.
EDIT3: I also noticed something:
Driver.Instance.SwitchTo().Frame(iframe);
Driver.Instance.FindElement(By.Id("tinymce")).SendKeys("message body");
It's the SECOND line that makes the cursor switch to the mce field, not the line with the .SwitchTo(). However, I need the first line - the second line does nothing on its own. This is approaching something really stupid. I've been looking for a solution to this for a week - this doesn't exactly bode well for Selenium. The Selenium user group doesn't even want to answer when I ask them.
Also - if I skip the SendKeys() method in the second line, nothing happens. So, it seems that the two lines does ALLMOST what it should, right up to and including placing the cursor in the correct spot. But it never sends any text.
EDIT4 (last): After actually figuring out how to use IJavaScriptExecutor, it works using the solution(s) below.

Java method to handle TinyMCE editor would look like:
public void entersTopicOfBody(String textToBeTyped, WebDriver driver) {
driver.switchTo().frame("content_ifr");
WebElement body = driver.findElement(By.xpath("//body"));
body.click();
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].innerHTML = '"+ textToBeTyped+"'", body);
driver.switchTo().defaultContent();
}

Below is some C# code that publishes a post. I think the main issues you have are due to timing issues.
I've done a bit of Selenium recently and I favour implicit waits: it waits for a maximum time period for the item to be available, but returns as soon as possible. So you can specify a max wait of 100 seconds, but if it finds it in 1 second, it will only wait 1 second. Much more efficient vs sleeping for an arbitrary length of time. See this post about Implicit and Explicit waits
But even with implicit waits, it may not solve all issues. When coding the sample below, I ran into the issue where the "Publish" button was disabled and re-enabled after some time. And that's when you have to look at the code to see what it is doing as well. It's times such as these where sleeps can help you fix the problem for a quick fix if you do not wish to debug too much: just be sure to set a large enough sleep time and be wary that it could be inconsistent in the future.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Support.Events;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
// enter your configurations here
driver.Navigate().GoToUrl("http://localhost/wordpress/wp-admin/post-new.php");
driver.FindElement(By.Id("user_login")).SendKeys("admin");
driver.FindElement(By.Id("user_pass")).SendKeys("yourpassword");
driver.FindElement(By.Id("wp-submit")).Click();
driver.FindElement(By.Id("title")).SendKeys("the title");
var iframe = driver.FindElement(By.Id("content_ifr"));
driver.SwitchTo().Frame(iframe);
// your solution which works in my instance
//driver.SwitchTo().ActiveElement().SendKeys("hello tiny mce from selenium");
// send keys with exact element
//driver.FindElement(By.Id("tinymce")).SendKeys("hello tiny mce from selenium");
// javascript - 1
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
var tinymce = driver.FindElement(By.Id("tinymce"));
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
executor.ExecuteScript("arguments[0].innerHTML = 'hello tiny mce via javascript'", tinymce);
// javascript - 0
driver.SwitchTo().DefaultContent();
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(11));
wait.Until((d) => { return !d.FindElement(By.Id("publish")).GetAttribute("class").Contains("disabled"); }); // wait for publish button to be enabled
driver.FindElement(By.Id("publish")).Click();
driver.FindElement(By.Id("message")); // wait for message on next page to verify it is posted
driver.Close();
}
}
}

A PHP version of olyv solution:
$content = 'my text';
$this->frame( 'content_ifr' );
$body = $this->byXPath( '//body' );
$body->click();
$script = 'arguments[0].innerHTML = "" + arguments[1] + ""; ';
$this->execute( [
'script' => $script,
'args' => [ $body->toWebDriverObject(), $content ],
]
);
$this->frame( null );

I know that I am a bit late to the party, but I just found a solution that is (I believe) much simpler than the answers given so far. So I decided to post it here in case it could help someone else.
There is no need to switch frames here. What you wanna do is 'click' on the button in the top right corner of the text editor that says "Text", which has id = "content-html". Now, you can 'send keys" to the textarea, which has id = "content".
Here is some Python code that does just this:
driver.find_element_by_id("content-html").click()
driver.find_element_by_id("content").send_keys("Some text...")
Hope it helps

Related

Meteor: send message to user at hot code push

How can I let the user know when they are getting a hot code push?
At the moment the screen will go blank during the push, and the user will feel it's rather weird. I want to reassure them the app is updating.
Is there a hook or something which I can use?
Here's the shortest solution I've found so far that doesn't require external packages:
var ALERT_DELAY = 3000;
var needToShowAlert = true;
Reload._onMigrate(function (retry) {
if (needToShowAlert) {
console.log('going to reload in 3 seconds...');
needToShowAlert = false;
_.delay(retry, ALERT_DELAY);
return [false];
} else {
return [true];
}
});
You can just copy that into the client code of your app and change two things:
Replace the console.log with an alert modal or something informing the user that the screen is about to reload.
Replace ALERT_DELAY with some number of milliseconds that you think are appropriate for the user to read the modal from (1).
Other notes
I'd recommend watching this video on Evented Mind, which explains what's going on in a little more detail.
You can also read the comments in the reload source for further enlightenment.
I can image more complex reload logic, especially around deciding when to allow a reload. Also see this pacakge for one possible implementation.
You could send something on Meteor.startup() in your client-side code. I personally use Bert to toast messages.

Retrieve comments from website using disqus

I would like to write a scraping script to retrieve comments from cnn articles. For example, this article: http://www.cnn.com/2012/01/19/politics/gop-debate/index.html?hpt=hp_t1
I realize that cnn uses disqus for their comment discussion. As the comment loading is not webpage-based (ie, prev page, next page) and is dynamic (ie, need to click "load next 25"), I have no idea how to retrieve all the 5000+ comments for this article.
Any idea or suggestion?
Thanks so much!
I needed to get comments via scraping a page that had disqus comments via ajax. Because they were not rendered on the server, I had to call the disqus api. In the source code, you will need the identifier code:
var identifier = "456643" // take note of this from the page source
// this is the ident url query param in the following js request
also,look in the js source code to get the pages public key, and forum name. Place these in the url where appropriate.
I used javascript nodejs to test this, ie :
var request = require("request");
var publicKey = "pILMw27bsbJsdfsdQDh9Eh0MzAgFL6xx0hYdsdsdfaIfBHRvLGqFFQ09st";
var disqusUri = "https://disqus.com/api/3.0/threads/listPosts.json?&api_key=" + publicKey + "&thread:ident=456643&forum=nameOfForumFromSource";
request(disqusUri, function(res,status,err){
console.log(res.body);
if(err){
console.log("ERR: " + err);
}
});
The option for scraping (other then getting the page), which might be less robust (depends on you're needs) but will offer a solution for the problem you have, is to use some kind of wrapper around a full fledged web browser and literally code the usage pattern and extract the relevant data. Since you didn't mention which programming language you know, I'll give 3 examples: 1) Watir - ruby, 2) Watin - IE & Firefox via .net, 3) Selenium - IE via C#/Java/Perl/PHP/Ruby/Python
I'll provide a little example using Watin & C#:
IE browser = new IE();
browser.GoTo(YOUR CNN URL);
List visibleComments = Browser.List(Find.ById("dsq-comments"));
//do your scraping thing
Link moreComments = Browser.Link(Find.ByClass("dsq-paginate-append-text");
moreComments.click();
//wait util ajax ended by searching for some indicator
Browser.WaitUntilContainsText(SOME TEXT);
//do your scraping thing
Notice:
I'm not familiar with disqus, but it might be a better option to force all the comments to show by looping the Link & click parts of the code I posted until all the comments are visible and the scrape the List element dsq-comments

Not sure why my program seems to be skipping some functions?

Hey there,
I'm a little confused with some Actionscript I'm working on. For my GUI, I have written four functions for times when computing is taking place. These are showMessage("Loading Text..."), disableButtons(), clearMessage(), and enableButtons(). They work great throughout the program. ShowMessage displays a loading message, disableButtons disables buttons so no one can click anything, clearMessage clears the loading message when job is done, and enableButtons turns them all back on.
For some reason, there is one button click handler which is giving me troubles and I'm not sure why. I've set it up just like others similar to it (which all work) but this one doesn't display the message or shut off my buttons. Here is my clickHandler...
private function Buffer_Route_clickHandler():void
{
showMessage("Loading RBE Options");
disableButtons();
if(Buffer_Route.selected && rbeAC.length == 0){
createRbeAC();
}
}
And here is the creatRbeAC function...
private function createRbeAC():void
{
rbeAC.removeAll();
hiddenRBELayers.removeAll();
var rbeIDs:Array = rbeConfigList.getKeySet();
for each (var rbeID:int in rbeIDs)
{
var rbeConfig:Hashtable = rbeConfigList.find(rbeID) as Hashtable;
var rbeData:Object =
{
restURL:rbeConfig.find("rbeRESTURL") as String,
layername:rbeConfig.find("rbeLayerName") as String,
icon: rbeConfig.find("rbeIcon") as String,
titlefield: rbeConfig.find("rbeTitleField") as String,
checked: rbeConfig.find("rbeChecked") as String,
count: "0" as String
};
if(rbeData.checked == "false")
{
hiddenRBELayers.addItem(rbeData.layername);// as String);
}
rbeAC.addItem(rbeData);
}
}
I wasn't getting any loading text, so I took out my clearMessage and enableButtons functions from the code to see if it was adding the message and disabling the buttons to begin with. I am still not getting anything though. Since clearMessage and enableButtons is no where to be found in this button click handler or creatRbeAC function, then I can not understand why the loading message and buttons aren't disabled, even when the computing is finished.
Some things to note. If I comment out the creatRbeAC function, the loading message shows and buttons do disable. Its almost as if those functions are being ignored when the creatRbeAC function is in the code.
Any help? I would greatly appreciate it. Hopefully I have provided enough information.
in my actual app, i have similiar problems.
In my Eventhandler (it doesn't matter, if there is a button handler or a mouse handler), I also wan't to disable the app and use some filter functions for my arrayCollection.
Unfortunately, this action seems to need too much ressources, especialy, when the app run in debug mode. I have to waint for the next screnn refresh. So i try to implement the "applyFilterMethod" in my eventhandler with
callLater(applyFilterMethod)
but it also wo't work.
Finally, the setTimeOut(applyFilterMethod,500)
solved my issue. So, try it with the timeout-method, if you have luck.
BR
Frank

Run Javascript on the body of a Gmail message

I want to display LaTeX math in the gmail messages that I receive, so that for example $\mathbb P^2$ would show as a nice formula. Now, there are several Javascripts available (for example, this one, or MathJax which would do the job, I just need to call them at the right time to manipulate the gmail message.
I know that this is possible to do in "basic HTML" and "print" views. Is it possible to do in the standard Gmail view? I tried to insert a call to the javascript right before the "canvas_frame" iframe, but that did not work.
My suspicion is that manipulating a Gmail message by any Javascript would be a major security flaw (think of all the malicious links one could insert) and that Google does everything to prevent this. And so the answer to my question is probably 'no'. Am I right in this?
Of course, it would be very easy for Google to implement viewing of LaTeX and MathML math simply by using MathJax on their servers. I made the corresponding Gmail Lab request, but no answer, and no interest from Google apparently.
So, again: is this possible to do without Google's cooperation, on the client side?
I think one of the better ways to do this might be to embed images using the Google Charts API.
<img src="http://chart.apis.google.com/chart?cht=tx&chl=x=\frac{-b%20\pm%20\sqrt{b^2-4ac}}{2a}">
To Learn more: https://developers.google.com/chart/image/ [note, the API has been officially deprecated, but will work until April 2015]
If you really must use LaTeX and some js library, I think one way you could accomplish this is by injecting a script tag into the iframe.
I hope this is a good starting point.
Example:
// ==UserScript==
// #name Test Gmail Alterations
// #version 1
// #author Justen
// #description Test Alter Email
// #include https://mail.google.com/mail/*
// #include http://mail.google.com/mail/*
// #license GPL version 3 or any later version; http://www.gnu.org/copyleft/gpl.html
// ==/UserScript==
(function GmailIframeInject() {
GM_log('Starting GMail iFrame Injection');
var GmailCode = function() {
// Your code here;
// The ':pd' (div id) changes, so you might have to do some extra work
var mail = document.getElementById(':pd');
mail.innerHTML = '<h1>Hello, World!</h1>';
};
var iframe = document.getElementById('canvas_frame');
var doc = null;
if( iframe ) {
GM_log('Got iFrame');
doc = iframe.contentDocument;
} else {
GM_log('ERROR: Could not get iframe with id canvas_frame');
return
}
if( doc ) {
GM_log('Injecting GmailCode');
var code = "(" + GmailCode + ")();"
doc.body.appendChild(doc.createElement('script')).innerHTML=code;
} else {
GM_log('ERROR: Could not get iframe content document');
return;
}
})();
Well, there are already greasemonkey scripts that do things to GMail as far as i know (like this one). Is this a possible security hole? Of course, anything you'd do with executable code has that risk. Google seems to move a glacial speeds on things they're not interested in. They really do seem to function based on internal championing of ideas, so best way forward is to go find sympathetic googlers, if you want them to include something into GMail. Otherwise stick to Greasemonkey, at least you'll have an easy install path for other people who'd like to see the same functionality.

Loading extJS Combo Remotely not Working

This is my first bash at using extJS, and after a few hours of struggling, some things are working OK, except I have combo lists that I can't filter down to less than 2000 items in edge cases, so I'm trying to page the lists through remotely, but I must be doing something wrong.
My data store and combo look as follows:
var remoteStore = new Ext.data.JsonStore({
//autoLoad : true,
url : 'addition-lists.aspx',
fields : [{name: 'extension_id'}, {name: 'extension'}],
root : 'extensionList',
id : 'remoteStore'
});
.
.
xtype : 'combo',
fieldLabel : 'Remote',
name : 'remote',
displayField : 'extension',
valueField : 'extension_id',
mode : 'remote',
//pageSize : 20,
triggerAction : 'query',
typeAhead : true,
store : remoteStore,
anchor : '95%'
The combo works loading locally, but as soon as I switch to remote it remains blank.
My ASP.NET page returning the JSON is like this:
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.Write(GetRemote());
}
On remote stores the combo defaults its minChars property to 4, so the query only gets sent after typing 4 chars. Setting minChars almost gives the desired behaviour.
I say almost because even if the item sought by autocomplete is in the current page, a new server query still gets sent, defaulting the selection to the first item in the new page.
The way you configured your store above, the result from your ASP script should read something like this:
{"extensionList": [
{"extension_id": 1, "extension": "js"},
{"extension_id": 2, "extension": "aspx"}
]}
If it doesn't look like that, your remote store will not find anything.
You can refer to this question ExtJS combobox problem in IE
Several things. First, when doing this:
remoteStore.loadData(<%= GetRemote() %>);
you are not actually making a remote call from your javascript. You are echoing the result of calling the GetRemote server function directly into the page at render time. Probably not what you intend? If GetRemote is writing out your combo data (and it's working correctly), then you should be able to use a combo setup for local data. If the intention really is to make a remote call, then you need to remove the server tag and load data via the proxy url as shown in several examples that come with Ext.
Another thing is that your Page_Load code doesn't actually show anything about how you are loading, formatting or returning your data. I would suggest viewing source and verifying that your tag is actually being replaced with the data you expect. If/when you switch it to a true remote call to load data then you can use Firebug to inspect your XHR calls and verify the data coming down that way.
You must set a proxy, i.e. set
proxy: new ScriptTagProxy
property for loading 'store' remotely. Look at examples for exact syntax.
EDIT: Please disregard my previous note since you're using JsonStore shortcut.
Try to apply all of these properties to your combo:
typeAhead: true,
typeAheadDelay: 500,
triggerAction: 'all',
selectOnFocus:true,
And please do not do server-side prefetch of records (using loadData). It hurts internal filter very much, so that you stick with filtered records from different prefetches.
On the other hand, if you do prefetch all records on the server-side, why do you need then remote access for your combo anymore?!

Resources