1

我想从以下标签中从网站“ 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。

4

1 回答 1

0

即使锚点没有类名和唯一 id,href: 中也有一个模式{site}/{brand}/{productname}/{productid}/product-detail

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

另一方面,要在网页上下文中选择 -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();
});
于 2013-10-23T11:08:16.410 回答