我想从以下标记中从站点“ http://www.firstcry.com/teethers-and-soothers/5/98?ref2=menu_dd”中刮取产品网址:

     <a href="http://www.firstcry.com/nuby/nuby-orthodontic-pacifier/140905/product-detail" id="ctl00_ContentPlaceHolder1_productdisplay_gvProductListDetails_ctl01_lnk_Image" onclick="jmp(this)">
                                <img id="ctl00_ContentPlaceHolder1_productdisplay_gvProductListDetails_ctl01_Img_view" title="Nuby - Orthodontic Pacifier" class="resizeimg" src="http://cdn.firstcry.com/brainbees/images/products/bigthumb/140905a.jpg" alt="Nuby - Orthodontic Pacifier" style="border-width:0px;border: none;vertical-align: middle;" original="http://cdn.firstcry.com/brainbees/images/products/bigthumb/140905a.jpg">

                                    </a>


我想做这样的事情:

     return [].map.call(document.querySelectorAll('a)'), function(link) {
        return link.getAttribute('href');
    });


由于此元素没有类名,并且所有产品的ID也不同,因此我不知道该怎么做。如果可以的话,我也不知道在幻影中使用x-path。

最佳答案

即使anchor没有类名和唯一ID,在href:{site}/{brand}/{productname}/{productid}/product-detail中也有一个模式。

特别是,恒定的产品详细信息将帮助我们选择产品网址。

另一方面,要在网页的上下文中选择-serialize-元素,则应使用page.evaluate

这是一个可能的脚本

var page = require('webpage').create();
var url = 'http://www.firstcry.com/teethers-and-soothers/5/98?ref2=menu_dd';

page.open(url, function(status) {
    // list all the a.href links
    var alllinks = page.evaluate(function() {
        return [].map.call(document.querySelectorAll('a'), function(link) {
            return link.getAttribute('href');
        }).filter(function(link) {return (link?link:'').indexOf('product-detail')>-1;});
    });

    console.log(alllinks.join('\n'));
    phantom.exit();
});

09-25 16:24
查看更多