简体   繁体   English

将cheerio对象转换为字符串

[英]Convert cheerio object to string

I am extracting metatags from page:我正在从页面中提取元标记:

$ = cheerio.load(html)
metaTags = $('meta')

and it works fine, but I need that metaTags array contain strings - not objects of cherrio, like here:它工作正常,但我需要metaTags数组包含字符串 - 而不是 cherrio 的对象,如下所示:

["<'meta something=1231'><'/meta'>", "<'meta sometag=44242'><'/meta'>"] ["<'meta something=1231'><'/meta'>", "<'meta sometag=44242'><'/meta'>"]

ps I dont need ' character it just stackoverflow.com missunderstaning ps我不需要'字符它只是stackoverflow.com misunderstaning

I have made such , method:我做了这样的,方法:

toHtml = (el) ->
  return el.html()

but it doesnt work : getting empty results (using map with it)但它不起作用:得到空结果(使用地图)

metaTags.map (i, el) -> console.log i.toHtml(el) metaTags.map (i, el) -> console.log i.toHtml(el)

let arrayOfHTMLstrings = $('meta').toArray().map( (el, index) => el.toString() );

根据cheerio官方文档

Here you have a solution:在这里你有一个解决方案:

findMetaTags = (html) ->
  $ = cheerio.load(html)

  metatagsContainer = $('<p>')
  $('meta').each ->
    metatagsContainer.append $(this).clone()

  unless _.isEmpty(metatagsContainer)
    return metatagsContainer.html()

  return
var cheerio = require('cheerio')
var html = 'SOME_HTML_STRING'
var $ = cheerio.load(html)
var htmlString = $.html()

I had problems with all of the answers here.我对这里的所有答案都有问题。

myNode.html() didn't find html() method in a lot of cases I tried. myNode.html()在我尝试过的很多情况下都没有找到html()方法。 myNode.toString() returned [object Object] . myNode.toString()返回[object Object]

What finally worked every time was using the html() method on the cheerio itself.每次最终都有效的是在cheerio 本身上使用 html() 方法。

const cheerio = require("cheerio")
cheerio.html( myNode )

This will convert any node to html string, in a loop or otherwise.这将在循环或其他方式中将任何节点转换为 html 字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM