访问和填充 div 元素的特定出现

Accessing and populating a specific occurence of div element

这是网页的html部分

<div id="upload" class="panel">
        <div style="width:720px" align="left">
            <table border="0"><tr>
                <td>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                </td>
                <td>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                </td>
                <td>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                    <div><input name="attachment[]" type="file"></div>
                </td>
            </tr></table>
</div>

我填充文件类型输入

page.uploadFile('input[type=file]', 'test2.png');

这总是填充第一个 div 输入附件文件类型。

如何更改它以填充 first/second...直到第十五 div 元素文件类型?

似乎 page.uploadfile 只接受类似 CSS 的简单选择器,但没有像 nth-child 这样的额外修饰符,因此无法定位所有输入,除非它们有自己的 类 或 IDs.

但是...我们可以用 page.evaluate 操作页面!让我们给他们独特的 类:

total_inputs = page.evaluate(function(){
    // Assign different class names to all file inputs
    var inputs = document.querySelectorAll('input[type=file]'), i;
    for (i = 0; i < inputs.length; ++i) {
        inputs[i].className = "file" + i;
    }
    // pass back to PhantomJS scope information about how many inputs there are
    return inputs.length;
});

// Now upload those files!
for (q = 0; q < total_inputs; ++q) {
    page.uploadFile('input[class=file' + q + ']', 'test2.png');
}

结果:

请注意,某些版本的 PhantomJS 无法上传文件。