简体   繁体   中英

Puppeteer how to specify a button if there are multiple buttons of that same class type?

I'm trying to use Puppeteer to click on a button.

The webpage in my script has a grid which acts as a calendar and each date is a button. The issue is that every date button is of the same class type and I so I couldn't single out a specific date.

I tried to identify the buttons by the aria label it still wouldn't work.

I then tried to click the "Go Forward 5 Days" button using the aria label and that didn't work either.

I have read that it might be available by iterating through the parent element in the HTML tree and then just picking the one that I want (example: putting the calendar element into a variable and then choosing the child I want[7]), but this really isn't ideal and I'm hoping there is another way.

const puppeteer = require ('puppeteer');

async function Main()
{
    const browser = await puppeteer.launch({product: 'chrome', headless: false});
    const page1 = await browser.newPage();
    const url1 = 'https://www.recreation.gov/camping/campgrounds/232446/availability';
    await page1.goto(url1);
    return page1;
}

async function selectDates(page){
    const button = await page.$('aria/Go Forward 5 Days[role="button"]');
    await button.click();
}

async function startCheckout()
{
    const page = await Main();
    await selectDates(page);
}

startCheckout();

Here's the button in HTML if it helps any:

<button class="rec-availability-date" aria-label="Jun 10, 2021 - Not Available">X</button>

The correct syntax for selecting DOM elements via their attributes is this:

// Click "5 days > "
await page.click('[aria-label="Go Forward 5 Days"]');

// Click a specific day:
await page.click('[aria-label="Jun 17, 2021 - Site 091 is available"]');

// Add to cart
await page.WaitForSelector('button.availability-page-book-now-button-tracker');
await page.click('button.availability-page-book-now-button-tracker');

Also see these articles on selecting elements via attributes:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM