【问题标题】:Parse text from HTML form inside table cell with Cheerio使用 Cheerio 从表格单元格内的 HTML 表单中解析文本
【发布时间】:2018-05-30 03:24:58
【问题描述】:

我有一个如下所示的 HTML 表格:

<tr class="row-class" role="row">
    <td>Text1</td>
    <td>
        <form method='get' action='http://example.php'> 

            <input type='hidden' name='id_num' value='ABCD123'> <!-- < I NEED THIS VALUE -->

            <button type='submit' class='btn' title='Check' ></button> 
        </form>
    </td>  
</tr>

我想获取名为id_num的隐藏输入类型的值。(在本例中,我想要的值是“ABCD123”)。

我尝试使用cheerio 解析代码,如下所示:

var $ = cheerio.load(body);
$('tr').each(function(i, tr){
    var children = $(this).children();

    var x       = children.eq(0);
    var id_num  = children.eq(1);

    var row = {
        "x":        x.text().trim(),     //this is correct, value is Text1
        "id_num":   id_num.text().trim() //This is empty, value is "", I want the value "ABCD123"
    };
});

但我只得到正确的第一个值。

如何从隐藏的输入元素id_num获取值?

谢谢。

【问题讨论】:

    标签: javascript html node.js html-table cheerio


    【解决方案1】:

    编辑

    你的eq(1) 得到了整个&lt;tr&gt;,试试这个吧:

    $('tr').each(function(i, tr){
          var children = $(this).children('td');
          var x        = $(children[0]);
          var id_num   = $(children[1]).find("input[name='id_num']");
          var row = {
              "x":        x.text(),
              "id_num":   id_num.val()
          };
    }
    

    【讨论】:

    • 谢谢,但有了这个我得到 id_num = Undefined :(
    • @Ford1892 哦,现在我明白了,请看我的编辑!
    【解决方案2】:

    应该是:

    $(tr).find('[name="id_num"]').attr('value')
    

    【讨论】:

    • 这个解决方案100%正确,谢谢!我选择了另一个作为答案,因为它与我之前编写的代码更相似。
    • 虽然它是不必要的混乱。不要乱用children,当你可以用css轻松得到你需要的东西时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多