nightmare - 如何使用 NightmareJS 3.0.1 从选项标签中选择 innerText 和 value
问题描述
我正在处理一些事情,发现我可以轻松地连接两个返回的数组,但它不是很干燥......你会怎么做呢????我需要选项文本和值,因为它们是不同的东西,但需要将它们返回到同一个对象中,以便我可以处理返回的所述值......如果我能以某种方式映射减少它,那么最好函数返回一个更好的键/值对象,但我不确定这是否可能:
//define a new Nightmare method named "textExtract"
//note that it takes a selector as a parameter
Nightmare.action('textExtract', function(selector, done) {
//`this` is the Nightmare instance
this.evaluate_now((selector) => {
//query the document for all elements that match `selector`
//note that `document.querySelectorAll` returns a DOM list, not an array
//as such, convert the result to an Array with `Array.from`
//return the array result
text = Array.from(document.querySelectorAll(selector))
//extract and return the text for each element matched
.map((element) => element.text );
elValues = Array.from(document.querySelectorAll(selector))
//extract and return the text for each element matched
.map((element) => element.value );
return text.concat(elValues)
//pass done as the first argument, other arguments following
}, done, selector)
});
引用自github。
解决方案
这个怎么样:
Nightmare.action('textExtract', function(selector, done) {
this.evaluate_now((selector) => {
return Array.from(document.querySelectorAll(selector))
.map(o => ({value: o.value, text: o.text}))
}, done, selector)
})
结果如下:
[
{ text: 'Bob', value: '766' },
{ text: 'Renee', value: '768' },
{ text: 'Paul', value: '787' }
]
推荐阅读
- spring-boot - 使用 Junit 5 测试 Pageable 本机查询每页返回的元素数量超过允许的数量
- vimeo - 如何最好地从 Vimeo Analytics 自动提取报告?
- vue.js - Quasar 浏览器扩展无法构建,开发工作正常
- php - PHP - 解析 HTML,选择标签,在所选标签内插入另一个 HTML 字符串
- javascript - 有没有办法将动作绑定到不是 Angular 上某个键绑定的每个击键?
- html - 为什么我的页面中的 col-md-6 显示全宽?
- c++ - 删除链表 C++ 中的特定节点
- sql - Apex Oracle calendar When Select list value is null show all and when Select value is not null show filtered
- xpath - 如何单击柏树中跨度类下的链接
- r - 我在尝试连接 R Markdown 中的数据但在非 Markdown 文件中较早工作时遇到错误