Search code examples
javascriptcssnode.jspuppeteerwebautomation

How to click button based on user input?


e.g Site: https://www.jdsports.com.sg/product/white-adidas-ultraboost-21-primeblue-womens/16140531_jdsportssg/

const size = prompt('Size? ')
page.evaluate(size => {
const elements = [...document.querySelectorAll('btn btn-default  ')];
const targetElement = elements.find(e => e.innerText.includes(size));
targetElement && targetElement.click();
}, size);

Im using puppeteer. At the moment i am trying to get the automation to click on the size based on the users input. Above is the current code I have but it isn't working.

heres how an product size button html:

<button data-e2e="pdp-productDetails-size" type="button" class="btn btn-default  " data-price="SGD 260.00" data-sku="16140531_jdsportssg.2910757" data-upc="4064036981142" data-fulfilment-infopage="" data-pool=" 1 " data-stockcheckeravailable="0" data-stock="1" title="Select Size 4">
            4
    </button>

So im trying to click the button based on the text. Thank you in advance!


Solution

  • You can try it this way.

    await page.evaluate(size => {
      Array.from(document.getElementsByClassName('btn btn-default')).filter(e => {
        return e.innerText == size
      }).forEach(element => {
        if (element) element.click();
      });
    }, size);
    

    By the way if you are going to use e.innerText.includes(size) and someone puts in size 5 into the prompt it will check the selector for anything that contains a size 5.

    For example:

    There are sizes 4, 4.5, 5, 5.5, 6, 6.5 And i pick size 5.

    e.innerText.includes('5') will pick any of them that contains the number 5 so it could even pick the size 4.5.

    You could try.

    await page.evaluate(size => {
      const elements = [...document.querySelectorAll('#itemOptions .options .btn')];
      const targetElement = elements.find(e => e.innerText == size);
    }, size);
    

    You could also use.

    await page.evaluate(size => {
      Array.from(document.querySelectorAll('#itemOptions .options .btn')).filter(e => e.innerText == size).forEach(e => e.click());
    }, size)