2

I am using Python headless browser library Pyppeteer. It's basically the same as Puppeteer (JS). So solutions which work on Puppeteer should work here too. I need a button to be clicked. Problem is that this button is dynamically generated and its id changes everytime:

Button

<button type="submit" class="btn btn-secondary" id="single_button5ea4a114318a96" title="">Upgrade Moodle database now</button>

Code

   async def configure(self):
   browser = await launch()
   page = await browser.newPage()
   await page.goto('mysite.example')
   await asyncio.gather(
   page.waitForSelector('button[title="Upgrade Moodle database now"]', timeout=60000),
   page.click('button[title="Upgrade Moodle database now"]')
   )

I could find that button from that part of its name which doesnt change single_button but there are 3 more buttons which ids starting single_button

Other buttons in the page:

<button type="submit" class="btn btn-secondary" id="single_button5ea4a114318a95" title="">Cancel new installations (2)</button>
<button type="submit" class="btn btn-secondary" id="single_button5ea4a114318a93" title="">Cancel this installation</button>
<button type="submit" class="btn btn-secondary" id="single_button5ea4a114318a94" title="">Cancel this installation</button>

Two things which makes this button unique are its id last number and title It would be appreciated if you could help me how to hit this button by its title.

Thank you guys!

Community
  • 1
  • 1
mike
  • 101
  • 1
  • 15

2 Answers2

0

Retrieve a more complete CSS selector. One can do this in Firefox Dev Tools by right clicking the the element > copy > CSS Selector

Mattwmaster58
  • 2,266
  • 3
  • 23
  • 36
0

Simple, use contains text XPATH selector:
//button[@type='submit' and contains(., 'Upgrade')]

Instead using waitForSelector, use a simple while loop until this element is found. Remember to create a timeout to avoid infinite loop.

from time import sleep, process_time

...

start = process_time()
btn = []
while len(btn) == 0:
    elapsed = process_time() - start
    if elapsed > 0.30:
        break  # timeout 30s
    btn = await page.xpath('//button[@type="submit" and contains(., "Entrar")]')
    sleep(1)
Luiz Vaz
  • 1,669
  • 1
  • 19
  • 32