Home > Blockchain >  Puppeteer: Is it possible to use click on a class with space in it?
Puppeteer: Is it possible to use click on a class with space in it?

Time:10-03

await page.waitForSelector(".Buttonstyled__StyledButton-sc-140xkaw-1 btsair BasketButton__StyledButton-sc-1qvc90d-0 cvuMvs");
await page.click(".Buttonstyled__StyledButton-sc-140xkaw-1 btsair BasketButton__StyledButton-sc-1qvc90d-0 cvuMvs");

I'll always get this TimeoutError: waiting for selector '.Buttonstyled__StyledButton-sc-140xkaw-1 btsair BasketButton__StyledButton-sc-1qvc90d-0 cvuMvs' failed: timeout 30000ms exceeded error and I suspect that it may have to do with the fact, that there are spaces in the name of the class. Here is how the button I want to click looks like when inspecting

CodePudding user response:

If an element's class attribute contains a space, it simply means there are multiple class names assigned to it. You could just place a period where those spaces are in the selector like so:

await page.waitForSelector(".Buttonstyled__StyledButton-sc-140xkaw-1.btsair.BasketButton__StyledButton-sc-1qvc90d-0.cvuMvs");
await page.click(".Buttonstyled__StyledButton-sc-140xkaw-1.btsair.BasketButton__StyledButton-sc-1qvc90d-0.cvuMvs");

CodePudding user response:

The HTML class attribute is a space-separated list of class names, so there can never be a class with a space in its name, only an element which has multiple classes.

Meanwhile, in a CSS selector, a space is used to represent "any descendent", so ".foo bar" means "find an element matching .foo, then find any descendent of that which matches bar". The ".foo" means "has class foo", the "bar" means "the tag name is bar". So your selector is looking for completely the wrong thing, even though it looks reasonable at first glance.

To say "must have both class foo and class bar", the CSS selector would be ".foo.bar" (note that there is no space, and both classes are preceded by a dot). So in your case, the element would match ".Buttonstyled__StyledButton-sc-140xkaw-1.btsair.BasketButton__StyledButton-sc-1qvc90d-0.cvuMvs", or ".btsair.cvuMvs.BasketButton__StyledButton-sc-1qvc90d-0", or any other order or subset.

Possibly though you just want a simpler selector, such as ".btsair".

A more reliable thing to look for is probably the id of the element, which is a single string identifying a single element in the document. For that, you use a '#' prefix, so for your example would write "#php-add-to-cart-button".

  • Related