node.js x-ray库如何校验表格td内容匹配指定值并生成布尔属性
解决方法
你可以通过两种方式实现需求,第一种是拿到抓取结果后直接遍历处理,第二种是利用x-ray的自定义字段处理逻辑在抓取时直接生成属性:
方法1:抓取完成后遍历追加属性(最直观,无需额外配置)
xray("https://free-proxy-list.net/", '#list tbody tr', [{ ip: 'td:nth-child(1)', port: 'td:nth-child(2)', code: 'td:nth-child(3)', country: 'td:nth-child(4)', anonymity: 'td:nth-child(5)', google: 'td:nth-child(6)', https: 'td:nth-child(7)' }])((err, proxies) => { if (err) throw err; // 遍历每个代理项新增属性 const processedProxies = proxies.map(proxy => { return { ...proxy, _proto: proxy.https.trim().toLowerCase() === 'yes' } }); console.log(processedProxies); });
代码中新增了trim()和toLowerCase()处理,是为了避免抓取到的内容存在空格、大小写差异导致判断出错。
方法2:在x-ray字段定义中直接生成属性
如果你不想后续遍历处理,也可以直接在字段定义里使用回调函数实时计算属性值:
xray("https://free-proxy-list.net/", '#list tbody tr', [{ ip: 'td:nth-child(1)', port: 'td:nth-child(2)', code: 'td:nth-child(3)', country: 'td:nth-child(4)', anonymity: 'td:nth-child(5)', google: 'td:nth-child(6)', https: 'td:nth-child(7)', // 直接定义_proto字段,通过DOM查询判断取值 _proto: (el) => el.querySelector('td:nth-child(7)').textContent.trim().toLowerCase() === 'yes' }])((err, proxies) => { if (err) throw err; console.log(proxies); });
内容的提问来源于stack exchange,提问作者Lakshaya U.
相关产品推荐
相关产品推荐

