I am using Puppeteer to automate a UI. I need to fetch an attribute value of a certain element, and I am using xpath to locate the element.
xpath:
//div[text()="5546800"]//following::div[@col-id="21"] .
I am getting an error "Failed to execute 'queryselector' on 'Document:
//div[text()="5546800"]//following::div[@col-id="21"] is not a valid selector
Below is the code I used:
const attributes=await page.$eval('//div[text()="5546800"]//following::div[@col-id="21"]',el =>el.getAttributes('type'))
You can't use XPath expressions in page.$eval, but you can create elementHandle with page.$x that can be passed to page.evaluate:
const attributes = await page.evaluate(el => el.getAttribute('type'), (await page.$x('//div[text()="5546800"]//following::div[@col-id="21"]'))[0])
FYI: I am not sure if you wanted to use getAttributes() and not getAttribute() or getAttributeNames().
Sorry, I made two typos in the previous version of this answer:
$x returns an array of element handles (just like $$ and not like $) so you need to use an index of the desired element. You also need to group the await-ed expression with parenthesis!
await page.$x('//div[text()="5546800"]//following::div[@col-id="21"]') => (await page.$x('//div[text()="5546800"]//following::div[@col-id="21"]'))[0]