[英]Puppeteer - best standard practices
在木偶戲中進行常規操作的最佳(或標准)方法是什么?
考慮一下:
<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。
來自: 木偶文件
Carsten解決了我提出的問題的第二部分,我非常感謝他!
但是,他的第一部分解決方案無效。
這是我如何使其工作的方式:
const values = await page.evaluate(
() => [...document.querySelectorAll('.C2')]
.map(element => element.getAttribute('src'))
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.