简体   繁体   中英

CasperJS: reference to a DOM element in click event instead of selector

I have written a script to perform certain actions on a page using PhantomJS. Now I am trying to write the CasperJS script for the same.

The page I am using is this

I am trying to click on one of the sizes (34 in this case) and then Click on "Add to Bag" button.

Size 34 is supplied dynamically to the script. Here is how I am doing it in PhantomJS

var point = page.evaluate(function (sizeToSelect){
    var sizes = document.querySelectorAll('.size-desktop li.first.popover-options');
    var filter = Array.prototype.filter;
    var selected = filter.call(sizes, function(size){ return size.textContent == sizeToSelect });
    if(selected && selected.length){
        selected = selected[0].querySelector("span");
        return selected.getBoundingClientRect();
    } else {
        return  { "error": "size not available" }
    }
}, inputElements.size)


if (point) {
    page.sendEvent('click', (point.left + point.width / 2) , point.top + point.height / 2 );
}

I am able to find the exact DOM element to click by using a loop in this case. However, CasperJS documentation specifies that the click method expects a query Selector which can be a CSS selector or an XPATH selector. How can I achieve this in CasperJS?

Basically I am looking for XPATH selector or CSS selector for elements based on their content or maybe attributes in some cases.

You can use the XPath helper utility to produce valid XPath objects that CasperJS understands:

var x = require('casper').selectXPath;

Your code should be functionally equivalent to this:

var sizeToSelect = "34";
casper.thenClick(x("//*[contains(@class,'size-desktop')]//"+
    "li[contains(@class,'first') and contains(@class,'popover-options')]/"+
    "span[contains(text(),'"+sizeToSelect+"')]/"+
    ".."));

Note that there is a /.. at the end in order to move to the parent of the <span> element which is an <a> element and the one you want to click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM