I have some page with different products and should select randomly one of them. I have made test on javascript but have problems when trying to write it using node.js and selenium.
On my test page I got next structure
<div class="products">
<table width="600" cellspacing="6">
<tbody>
<tr>
<td>
<a href="phones-59.php"></a>
</td>
<td>...
</td>
</tr>
<tr>...</tr>
...
So next example is working on javascript and I got all links I need
links = document.getElementById('products').getElementsByTagName('a');
then I use random and select some link, something like this (got example here Choosing a link at random)
randomlink = Math.round(Math.random() * (links.length+1));
links[randomlink].click();
Nothing special, but when I have tried such trick in node.js I can't access to links. I got errors when trying to use click() and other functions
driver.findElement(webdriver.By.id('products')).findElements(webdriver.By.tagName('a'));
So how I can click on random link in my "products" block? Thanks
PS I have copied "unique selector' from firefox developers console, but have no idea how to use it in right way (I have tried use xpath without success)
"products > table:nth-child(1) > tbody:nth-child(1)"
update I have also tried such construction and got correct number of links, but can't access to them
ll = driver.findElement(webdriver.By.id('products'));
lk = ll.findElements(webdriver.By.tagName('a')).then(function(txt) {
logger.info("lk length: " + txt.length); });
Can you edit the html and give each one of the links their own unique IDs? I would do that and then create an array that contains all of the IDs. Choose a random ID and then use driver.findElement(webdriver.By.id(randomID[x])).click();
If you don't have permissions to edit the html you could do something similar with xpath. Add all the unique xpath selectors to an array and instead of findElement(webdriver.by.id(randomID[x])) use findelement(webdriver.by.xpath(randomXpath[x]));
Sorry if I didn't get the syntax entirely correct... I usually use selenium with C#.
Hope this helps!
It's very weird :) but it works
Example for Bing.Com
var webdriver = require('selenium-webdriver');
var logger = require('winston');
driver.get('http://bing.com');
driver.findElements(webdriver.By.tagName('a')).then(function(elems){
logger.info("links count: " + elems.length);
rnd = Math.round(Math.random() * (elems.length+1));
logger.info("rnd number: " + rnd);
elems[rnd].getText().then(function(textValue){
logger.info("link name: " + textValue);
});
elems[rnd].then(function (elem) {
elem.click();
});
});
I found answer here Node.js + Selenium How to parse html properly