简体   繁体   中英

How to click on dinamcly generated button using pyppeteer/puppeteer?

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!

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM