node.js - Puppeteer - 最佳标准实践
问题描述
在 puppeteer 上进行常见操作的最佳(或标准)方法是什么?
考虑一下:
<div class="C1">
<img alt="Bla Bla" class="C2" scrset="lots of stuff here" scr="THIS_IS_WHAT_I_WANT">
我想访问 src 文本。最好的方法是什么?
或者我在网页上有这个的另一种情况:
<a class="D1 D2 D3" role="button" </a>
我想检查像上面按钮这样的元素的存在(和不存在)。
解决方案
您的第一个示例(获取 src 文本):
const puppeteer = require('puppeteer')
async function run() {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto(`insertYourURLhere.com`, {
timeout: 0,
waitUntil: ['domcontentloaded']
})
// getting a handle on the div first
const outerDiv = await page.$('div.C1')
// proceeding from the selected div
const scrAttribut = await outerDiv.$eval('img.C2', el => el.getAttribute('scr'))
console.log(scrAttribut)
browser.close()
}
run()
您的第二个示例(检查元素的存在):
您使用与上面所示相同的方法来查找外部 div 按钮:
page.$(selector)
然后检查返回值。
如果没有元素匹配选择器,则返回值解析为null。
来自:Puppeteer 文档
推荐阅读
- html - 为什么这些 inline-block 元素在顶部和底部保留空白?
- amazon-sqs - 是否可以在 Java SDK 中设置 ARN 参数 role_arn?
- c# - 使用 RunSettings 文件指定相对文件路径
- javascript - 为什么“检查版本”步骤的这个实现仍然失败?
- java - 如何在不使用 kml 的情况下向 android studio 中的谷歌地图应用程序添加大量多边形
- wordpress - IIS 10 web.config 为上传的文件(如图像、pdf、docx)抛出 500
- python - 这个 python 代码中的“x=sorted(list(set(x for name,x in marksheet)))”是什么意思?
- r - dplyr 无法计算向量中的子字符串
- php - 如何检查相关表是否没有记录
- list - 从数据框列表中制作单个数据框