我花了很多时间来尝试从一个对象中使用 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
},
title
和 href
这个对象是什么?x-attribsNamespace
, children
, next
它们是每个对象都有的吗?1)你可以这样做。
listings[0].attribs.title
listings[0].attribs.href
但这是比较常见的。
$(listings[0]).attr('title')
$(listings[0]).attr('href')
2)它是一个parse5 Node对象,这让人很困惑,因为在jQuery中它应该是一个DOM节点。
你所看到的这种格式是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
根据你问题的第二部分, 这些字段不带有... ... 每一 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对象array,是的,cheerio对象有很多属性和功能,如 attr