You seem to have simply confused span
and h1
in your selector. However, I'd like to offer a few suggestions and notes to improve upon other answers.
- Always use booleans like true and false rather than strings
"Success"
and "Failed"
.
waitForXPath
throws when the timeout expires, so the if
is unnecessary.
- The second argument to
waitForXPath
should be {timeout: 30000}
rather than 30000
.
- Unless you override it elsewhere in your code, 30 seconds is the default timeout so you can omit that option.
- Scope variables with
let
or const
.
- Use the return value of
waitFor_
rather than re-selecting the element.
waitForXPath
is deprecated in favor of waitForSelector("::-p-xpath(...)")
.
Putting these suggestions together, we have:
const xp = '::-p-xpath(//h1[contains(text(), "Subscription Confirmed")])';
const el = await page.waitForSelector(xp);
const text = await el.evaluate(el => el.textContent);
You can wrap this in a try
/catch
if you expect failure, or use the shorthand:
const xp = '::-p-xpath(//h1[contains(text(), "Subscription Confirmed")])';
const el = await page.waitForSelector(xp).catch(() => null);
if (el) {
const text = await el.evaluate(el => el.textContent);
}
But we can improve this. Puppeteer now has the ::-p-text()
pseudoselector which is a bit more succinct:
const el = await page.waitForSelector("h1::-p-text(Subscription Confirmed)");
const text = await el.evaluate(el => el.textContent);
Now, since you're selecting by full text and not using a substring, you basically already know the text, so there's no point in getting it!
If you want to check whether specific text exists or not and you don't want to wait for it to appear, you can use:
const exists = await page.$("h1::-p-text(Subscription Confirmed)");
if (exists) {
// it exists
}
exists
will be null if not found or the ElementHandle otherwise. This seems closer to your original intent.
See this post for a canonical resource to selecting by text in Puppeteer.