如何用 Nokogiri 解析连续的标签? [英] How to parse consecutive tags with Nokogiri?

查看:51
本文介绍了如何用 Nokogiri 解析连续的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的 HTML 代码:

<dt>标签1</dt><dd>值1</dd><dt>标签2</dt><dd>值2</dd>...

我的代码不起作用.

doc.css("first").each do |item|label = item.css("dt")value = item.css("dd")结尾

首先显示所有 <dt> 标签,然后是 <dd> 标签,我需要label: value"

解决方案

首先,你的 HTML 应该有

元素在
中:

<dl><dt>标签1</dt><dd>值1</dd><dt>标签2</dt><dd>值2</dd>...</dl>

但这不会改变你解析它的方式.你想找到

并迭代它们,然后在每个
你可以使用 next_element 来获得
;像这样:

doc = Nokogiri::HTML('

...')doc.css('#first').search('dt').each do |node|puts "#{node.text}: #{node.next_element.text}"结尾

只要结构与您的示例相匹配,这应该有效.

I have HTML code like this:

<div id="first">
<dt>Label1</dt>
<dd>Value1</dd>

<dt>Label2</dt>
<dd>Value2</dd>

...
</div>

My code does not work.

doc.css("first").each do |item|
  label = item.css("dt")
  value = item.css("dd")
end

Show all the <dt> tags firsts and then the <dd> tags and I need "label: value"

解决方案

First of all, your HTML should have the <dt> and <dd> elements inside a <dl>:

<div id="first">
    <dl>
        <dt>Label1</dt>
        <dd>Value1</dd>
        <dt>Label2</dt>
        <dd>Value2</dd>
        ...
    </dl>
</div>

but that won't change how you parse it. You want to find the <dt>s and iterate over them, then at each <dt> you can use next_element to get the <dd>; something like this:

doc = Nokogiri::HTML('<div id="first"><dl>...')
doc.css('#first').search('dt').each do |node|
    puts "#{node.text}: #{node.next_element.text}"
end

That should work as long as the structure matches your example.

这篇关于如何用 Nokogiri 解析连续的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆