【问题标题】:How to specify the class selector in web scraping using nodejs如何使用nodejs在网络抓取中指定类选择器
【发布时间】:2012-04-02 13:09:18
【问题描述】:

我正在尝试使用 nodejs 实现抓取。我正在向特定的 url 发送请求,当我收到响应时,使用响应将页面中的每个产品存储到数组中。对于每个产品,我都在尝试显示产品详细信息,例如产品名称、价格和折扣等。我通过以下代码执行此操作。

var $products = $body.find('.fashion-item');
$products.each(function (i, item) {
    var $name = ($(item).find('.info .title').text(),
        $price=$(item).find('span.price.regular').text().substr(6),
        $discount=$(item).find('span.price.percentoff').text().slice(0,2);
    self.items[i] = {
        title: $name,
        price: $price,
        discount: $discount,
    };
});
console.log(self.items);

它工作正常。如果类名类似于“fashion-item”或“fashion-item-first”,所有这些都可以正常工作。但是,如果类名包含单词之间的空格,则不会将任何产品存储在数组 ($products) 中,即 $products 的数组长度为零。我的问题是,如果类名像这样的“时尚项目优先”,如何做同样的事情。我尝试了很多,但我没有任何想法。请帮帮我。

【问题讨论】:

    标签: node.js web-scraping jsdom


    【解决方案1】:

    类名不能有空格。在您的示例中,'fashion-item first' 是分配给一个元素的两个类,可以通过 .fashion-item.first 选择器进行选择。

    【讨论】:

      【解决方案2】:

      如果您想要同时具有信息和标题类的项目,请选择它们:

      $(item).find('.info.title')
      

      如果你想要这些类之一,使用这个

      $(item).find('.info,.title)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-16
        • 1970-01-01
        • 1970-01-01
        • 2019-02-22
        相关资源
        最近更新 更多