Estoy usando titiritero para extraer contenido de un sitio web. Tengo esta estructura de marcado HTML:
<li> <div class="kode_ticket_text"> <h6>Tennis</h6> <div class="ticket_title"> <h2>ATP</h2> <span>VS</span> <h2>Monte Carlo (Monaco), terra battuta</h2> </div> <p>11:00 AM</p> </div> <div class="ticket_btn"> <a href="https://example.com/event-live">Guarda Gratis</a> </div> </li>
Necesito obtener el enlace y todas las demás informaciones que son el nombre del evento, la hora de la transmisión y el tipo. como tengo una lista de li
, he decidido usar la función page.$$eval()
de titiritero, pero no estoy seguro de cómo proceder para acceder a toda la información que necesito porque hay muchos elementos HTML anidados y yo no creo que pueda acceder a él después de haber seleccionado todos los li
?
Este es el código de node.js que estoy usando en este momento
puppeteer.launch({ headless: false }).then( async (browser) => { const page = await browser.newPage() const navigationPromise = page.waitForNavigation() await page.goto('https://example.com/') //await page.setViewport({ width: 1280, height: 607 }) await page.waitForSelector('.form-content > .form-items > .form-button > a > .ibtn') await page.click('.form-content > .form-items > .form-button > a > .ibtn') await navigationPromise // await page.waitForSelector('.container > .row > .results-item > .kode_ticket_wraper > .container') // await page.click('.container > .row > .results-item > .kode_ticket_wraper > .container') // await page.waitForSelector('.container > .kode_ticket_list > li:nth-child(1) > .ticket_btn > a') // await page.click('.container > .kode_ticket_list > li:nth-child(1) > .ticket_btn > a') // await navigationPromise await page.waitForSelector('ul.kode_ticket_list > li') await page.$$eval('ul.kode_ticket_list > li', (el) => { // here I want to select all the li and if possible all the informations needed }) await browser.close() })
page.$$eval
's pageFunction devuelve una matriz de elementos HTML que puede iterar para profundizar en el DOM de cada elemento <li>
. Simplemente cree la estructura del Objeto que desea devolver y acceda a los elementos anidados con querySelector()
.
Por ejemplo:
const data = await page.$$eval('ul.kode_ticket_list > li', listElems => listElems.map(li => { return { link: li.querySelector('.ticket_btn > a').href, title: li.querySelector('.kode_ticket_text > h6').innerText, time: li.querySelector('.kode_ticket_text > p').innerText } }) ) console.log(data)
Producción:
[ { link: 'https://example.com/event-live-1', title: 'Tennis 1', time: '11:00 AM' }, { link: 'https://example.com/event-live-2', title: 'Tennis 2', time: '9:00 AM' }, { link: 'https://example.com/event-live-3', title: 'Tennis 3', time: '10:00 AM' } ]