简体   繁体   English

如何使用 pyppeteer/puppeteer 单击动态生成的按钮?

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

I am using Python headless browser library Pyppeteer.我正在使用 Python 无头浏览器库 Pyppeteer。 It's basically the same as Puppeteer (JS).它与 Puppeteer (JS) 基本相同。 So solutions which work on Puppeteer should work here too.所以在 Puppeteer 上工作的解决方案也应该在这里工作。 I need a button to be clicked.我需要一个按钮来点击。 Problem is that this button is dynamically generated and its id changes everytime:问题是这个按钮是动态生成的,并且它的 id 每次都会改变:

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我可以从它的名称的那部分找到那个按钮,它不会改变single_button但是还有 3 个按钮,它们的 ids 开始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.使这个按钮独一无二的两件事是它的 id 最后一个数字和标题如果你能帮助我如何通过它的标题点击这个按钮,我将不胜感激。

Thank you guys!感谢你们!

Retrieve a more complete CSS selector.检索更完整的 CSS 选择器。 One can do this in Firefox Dev Tools by right clicking the the element > copy > CSS Selector可以在 Firefox 开发工具中执行此操作,方法是右键单击元素 > 复制 > CSS 选择器

Simple, use contains text XPATH selector:简单,使用包含文本 XPATH 选择器:
//button[@type='submit' and contains(., 'Upgrade')]

Instead using waitForSelector, use a simple while loop until this element is found.而不是使用 waitForSelector,而是使用一个简单的 while 循环,直到找到此元素。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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