了解 Cheerio 对象并获取属性

Understanding Cheerio object and get attributes

我花了很多时间尝试使用 Cheerio 从对象中读取数据,所以我得到了一个对象:

  rp(options)
        .then(($) => {
          const listings = $('.listing-cards').first().find(".listing-link");

console.log(listings[0]; 

这将打印一个很长的对象,我只需要它的第一部分:

{
    type: 'tag',
    name: 'a',
    namespace: 'http://www.w3.org/1999/xhtml',
    attribs: [Object: null prototype] {
      class: ' display-inline-block listing-link\n',
      'data-listing-id': '8026543453',
      'data-palette-listing-image': '',
     href: 'https://www...........link comes here',
     target: '_blank',
     title: 'Product title'
    },
    'x-attribsNamespace': [Object: null prototype] {
      class: undefined,
      'data-listing-id': undefined,
      'data-palette-listing-image': undefined,
      href: undefined,
      target: undefined,
      title: undefined
    },
  1. 我如何从该对象中获取 titlehref
  2. 这个对象是什么?它是一个数组吗?里面剩下的东西是什么? ( x-attribsNamespace, children, next ?每个对象都有它们吗?

您正在查看的这种格式是 Javascript 中所有对象的表示方式。参见 json

您可以像这样访问 json 对象中的任何字段:

obj.fieldname 或等价地:obj[fieldname]。如果您知道字段名称是字符串,则第二种语法很有用。

因此,在您的示例中,您可以说:

const title = listings[0].title
const href = listings[0].attribs.href //notice there's nested json here. 'attribs' is an object itself

根据你的问题的第二部分,这些字段不带有 every javascript 对象。您可以很容易地创建一个没有这些字段的对象:

const obj = {
    myOnlyField: "Hello, world."
}

不过,您或许可以阅读 cheerio 文档,看看他们的库是否始终包含这些字段。

(1) 您应该参考 cheer.io 文档。你可以试试

const arrayOfObject = listings.map(function(i, el) {
  // this === el
  console.log($(this).attr('href'))
  return {
    title: $(this).attr('title'),
    href: $(this).attr('href')
  };
}).get();

(2) 这代表一个 cheerio 对象而不是普通的 javascript object/array 是的,cheerio 对象有许多属性和函数,如 attr

1) 你可以这样做:

listings[0].attribs.title
listings[0].attribs.href

但更常见的是:

$(listings[0]).attr('title')
$(listings[0]).attr('href')

2) 它是一个 parse5 节点对象,这很容易混淆,因为在 jQuery 中它将是一个 DOM 节点。