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" 
4
  • 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. Commented Feb 9, 2021 at 2: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. Commented Feb 9, 2021 at 9: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. Commented Feb 9, 2021 at 9: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: stackoverflow.com/questions/55017057/… and stackoverflow.com/questions/55388455/… Commented Feb 9, 2021 at 18:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.