對於點擊 <a target='_blank'>
標簽打開新 tab 頁的場景,Puppeteer目前(2019-03,v1.13.0)沒有現成的 API 支持。因此需要一些 walkaround 來解決。有幾個方案。
提取 href,手動打開新 page 去訪問
url = await page.evaluate('() => $("a").attr("href")')
detail_page = await browser.newPage()
# goto 帶了 waitForNavigation 的作用
await detail_page.goto(detail_page_url)
使用點擊,再去輪徇 pages
代碼如下。這個方案的問題在於,拿到 detail_page
時並不知道頁面是否 load
完成了,在這個時候調用 .waitForNavigation()
可能會超時報錯(因為沒有 load
事件被 fire
)。如果頁面有 AJAX 請求,你可能需要寫額外的 waitForSelector
來確保你要的數據已經在頁面上。
# 點擊完后出現新 tab 頁
await page.click(f'#panel-5 tr:nth-child({index + 1}) a')
# 等新 Tab 頁 ready,即 pages 中有新 tab 頁。由於沒有現成 API,只能靠等
detail_page = None
for i in range(5):
pages = await browser.pages()
try:
detail_page = next(page for page in pages if 'biangeng.html' in page.url)
except StopIteration:
await asyncio.sleep(1)
else:
break
if detail_page is None:
msg = "New page did not show up or show up so slowly."
logger.error(msg)
raise Exception(msg)