3

I have the following element in my code:

<div class="MuiButtonBase-root MuiListItem-root MuiListItem-gutters MuiListItem-button" tabindex="0" role="button" aria-disabled="false" id="1"><div class="MuiListItemText-root"><span class="MuiTypography-root MuiListItemText-primary MuiTypography-body1">Arne Nordman (arne@nordman.no)</span></div><span class="MuiTouchRipple-root"></span></div>

This element is a part of a drop-down list that appears after typing into a text field. Unfortunately, when I use the following code, the element can not be identified. It says "DOMException: Failed to execute 'querySelector' on 'Document': '#1' is not a valid selector".

Here is my code:

const puppeteer = require("puppeteer");

async function run() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  await page.goto("http://localhost:3000/");

  await page.evaluate(() =>
    [...document.querySelectorAll("button")].map(
      elem => elem.innerText === "Personell & Institutions" && elem.click()
    )
  );

  await page.type("input", "arne");
  await page.waitFor(1000);
  await page.$eval("#1", el => console.log("elemnet is:", el.innerText));
}

run();

Any help would be truly appreciated!

Machavity
  • 30,841
  • 27
  • 92
  • 100
Nora
  • 1,825
  • 8
  • 31
  • 47

1 Answers1

4

You can quote the "1" in the selector:

await page.$eval("#\\31", el => console.log("elemnet is:", el.innerText));

It's OK to have id values that aren't identifiers, but you run into the CSS syntax problems you're seeing.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thank you so much! For some reason that did not work, but I used [id='1'] instead based on your idea :) – Nora Nov 25 '19 at 14:13
  • @Nora sorry I'll fix the answer; it needs two backslashes to get past the string syntax. Your solution is also fine. – Pointy Nov 25 '19 at 14:16
  • Thank you! Really nice of you to help :D – Nora Nov 25 '19 at 14:20