0

I can't figure out why this piece of code not working:

var stock;
var stockEL = await page.$eval('.qty tbody tr td:nth-of-type(1) span');
if ( stockEL !== null) {
stock = stockEL.getAttribute('data-tip');
}

I am trying to use in Puppeteer. I would like to check if a span of first td exists, if yes, read the span attribute, if not exists do nothing.

 Error: Error: failed to find element matching selector ".qty tbody tr td:nth-of-type(1) span"
  • Do other selectors work? like `"div"`? Basically, I am trying to determine if the page is being loaded at all, or if it is being loaded, but the selector just doesn't exist on the loaded page. – Alex Wayne Feb 09 '21 at 02:08
  • 1
    Run your script in a headful mode, slow down execution speed, debug it. General advice to general question. Share the site or relevant DOM if you need more help. Your selector looks way too complicated, try to simplify it as well, one class, one attribute, one id is usually a solution. – pavelsaman Feb 09 '21 at 09:12
  • Perhaps you could try breaking it down bit by bit, look for '.qty' first then .qty tbody and so on until you get a failure - just to check your string is exactly correct. – A Haworth Feb 09 '21 at 09:14
  • 2
    Beware of two issues in your fragment: 1. `page.$eval()` needs a function as its second argument, so maybe you meant `page.$()` to get ElementHandle; 2. ElementHandle has no `getAttribute` method — it is not a DOM element. See the difference: https://stackoverflow.com/questions/55017057/puppeteer-returning-empty-object/55032557#55032557 and https://stackoverflow.com/questions/55388455/get-href-attribute-in-pupeteer-node-js/55391319#55391319 – vsemozhebuty Feb 09 '21 at 18:57

1 Answers1

0

try this variant await page.$(selector) or page.waitForSelector. Remember that $eval and $$eval needs a function as it's second argument.

[Example eval]

const data = await page.$$eval('selector', el => { /*code*/ });

[Example waitForSelector]

await page.waitForSelector('body > div.wrapper > aside > section > ul > li:nth-child(4) > a > span');

Here some useful links