Reputation: 3843
What is the best (or standard) way to do common operations on puppeteer?
Consider this:
<div class="C1">
<img alt="Bla Bla" class="C2" scrset="lots of stuff here" scr="THIS_IS_WHAT_I_WANT">
I want to acces the src text. What is the best way to do that?
Or another situation where i have this on the webpage:
<a class="D1 D2 D3" role="button" </a>
And i want to check the existence (and nonexistence) of an element like the above button.
Upvotes: 0
Views: 2146
Reputation: 3843
The second part of my asnwer was correclt solved by Carsten and i thank him very much!
However, his solution for the first part was not working.
Here's how i got it to work:
const values = await page.evaluate(
() => [...document.querySelectorAll('.C2')]
.map(element => element.getAttribute('src'))
);
Upvotes: 0
Reputation: 878
Your first example (getting the src text):
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()
Your second example (checking the existence of an element):
You use the same method as shown above for the outer div to find your button:
page.$(selector)
Then you check the return value.
If no element matches the selector, the return value resolve to null.
From: Puppeteer documentation
Upvotes: 2