使用pyppeteer,可以通过 .pages 功能获取所有打开的标签页。在网站自行打开新标签页之前(例如,单击按钮后),此方法可以正常工作。在这种情况下,新标签不会在**。pages *的返回中列出。
是否可以检测到这个新标签页,以便像其他标签页一样使用它?
(我没有用操纵up的手进行测试,但我认为它的行为相同。)
代码示例(很遗憾,我必须使用Python 2.7。所以我必须使用yield from):
self.browser = yield from launch(appMode=True, closeAtExit=False)
pages = yield from self.browser.pages()
self.page = pages[len(pages) - 1] # Open w3schools in the init tab
yield from self.page.goto("https://www.w3schools.com/tags/att_a_target.asp")
link = yield from self.page.waitForSelector('a.w3-btn:nth-child(4)')
yield from link.click()
yield from asyncio.sleep(5) # Just to give some extra time...
pages1 = yield from self.browser.pages()
self.log.info("Count: " + str(len(pages1))) # Should be 2 now
for mpage in pages1:
self.log.info("URL: " + str(mpage.url))
输出:
TARGETS: {'246562630E35EEAD0384B80658C827F8': <pyppeteer.target.Target object at 0x03482F10>}
TARGETS: {'246562630E35EEAD0384B80658C827F8': <pyppeteer.target.Target object at 0x03482F10>}
INFO:__main__:Count: 1
INFO:__main__:URL: https://www.w3schools.com/tags/att_a_target.asp
INFO:__main__:Done!