Home > Blockchain >  How to click on an a tag who's text matches a given string puppeteer
How to click on an a tag who's text matches a given string puppeteer

Time:03-01

I am trying to write a purchasing bot for supreme website as a way to teach myself javascript and pupetteer. I am having trouble finding a way to click on the item that contains the text that is given as an argument in the function. Here is what I am trying

'''

const puppeteer = require('puppeteer-extra');
const pluginStealth = require("puppeteer-extra-plugin-stealth");
puppeteer.use(pluginStealth());
const BASE_URL = "https://www.supremenewyork.com/shop/all";
const CHECKOUT_URL = "https://www.supremenewyork.com/checkout";

async function startBot(itemCategory) {

    const browser = await puppeteer.launch({
        args: ['--no-sandbox', '--disable-setuid-sandbox'],
        headless: false 
     });

    let page = await browser.newPage();
    await page.goto(itemCategory);
    return {page};

}

async function closeBrowser(browser) {

    return browser.close();

}

async function addToCart(page, itemName) {
    page.$$eval('a', as => as.find(a => a.innerText.match(itemName).click()));
}

async function checkout() {

    const page = await startBot(categories['t_shirts']);
    await addToCart(page, item_info['name']);

}

checkout();

'''

The error I get is: TypeError: page.$x is not a function

Am I going about this the correct way or is there a better method This is a brief overview of the HTML

<div >
    <a style="height:150px;" href="/shop/t-shirts/kw2h4jdue/dvor2fh76"><img width="150" height="150" src="//assets.supremenewyork.com/231423/vi/u13QfMEqLmM.jpg" alt="U13qfmeqlmm">
    </a>
        <h1>
            <a  href="/shop/t-shirts/kw2h4jdue/dvor2fh76">Knowledge Tee
            </a>
        </h1>
         <p>
              <a  href="/shop/t-shirts/kw2h4jdue/dvor2fh76">Black
           </a>
         </p>
</div>

I want to click the a class thats text is 'Knowledge Tee'

Thanks

CodePudding user response:

page.$x should be a function I think so something else is going wrong there.

You can also do something like:

page.$$eval('a', as => as.find(a => a.innerText.match("Knowledge Tee").click()))
  • Related