首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery/Cheerio:通过循环将标签之间的内容推送到JSON

问Jquery/Cheerio:通过循环将标签之间的内容推送到JSON
EN

Stack Overflow用户
提问于 2017-12-22 18:54:45
回答 1查看 95关注 0票数 0

尝试将来自十几个类似网页的数据放到JSON中。页面的结构是定义的,但每个块的数量可能会有所不同:

​

代码语言:javascript
复制
<h2>Block1</h2>
	<p><strong>Title1</strong></p>
		<p>content</p>
		
		<!–– the amount of p with content may vary ––>
		
		<p>content</p>
		<p>content</p>
	
	<!–– the amount of p with highlighted title may vary ––>
	
	<p><strong>Title_N</strong></p>
		<p>content</p>
		<p>content</p>
	
<!–– the amount of h2 blocks may vary ––>
 
<h2>Block_N</h2>
	<p><strong>Other_Title</strong></p>
		<p>content</p>

​

我试图像下面这样形成一个JSON,但是当它们在同一层次结构中,并且它们的数量是不确定的时候,在标签之间迭代标签有困难:

代码语言:javascript
复制
result.push({ 
BlockName: $('.frame h2').text(),
BlockContent:[{
    TitleName1: $('.frame p>strong:nth-of-class(1)').text(),
        TitleContent1[{
            Content1:$('.frame p>strong:nth-of-class(1)').nextUntil($('.frame p>strong:nth-of-class(2)')).each(///),
            Content2:$('.frame p>strong:nth-of-class(2)').nextUntil($('.frame p>strong:nth-of-class(3)')).each(///)),
            ///
            ContentN:$('.frame p>strong:nth-of-class(Last-1)').nextUntil($('.frame p>strong:nth-of-class(LastOne)')).each(///),
                    }],
            ///     
            }],
        })

所以我甚至不能指定我应该收集每个条目的数据的确切的标签。有没有办法不把所有标签的索引都存储在各自的变量中?

例如-降低created flat JSON中某些条目的层次结构:like this

我应该尝试什么方法?

感谢您的帮助,谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-23 00:56:01

我写了一个肮脏的例子,你可以从中获得灵感,输出变量应该符合你的规范!

我使用js遍历DOM的所有节点,并使用节点的类型(HTMLParagraphElement等)确定它是块的名称、标题还是内容。

代码语言:javascript
复制
Array.prototype.slice.call(dom.children).forEach((node) => {
  if (node instanceof HTMLHeadingElement) {
    if (Object.keys(currentBlock).length !== 0) {

JSFiddle:https://jsfiddle.net/z7dmwd7d/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47940300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档