pyppeteer文件下載

須要pyppeteer下載文件,網上沒什麼資料,本身摸索了下。less

def check_file(path):#利用文件下載以後,是否存在這個文件來判斷下載是否成功,
    while not bool(os.listdir('C:/' + path)):
        pass
    return bool(os.listdir('C:/' + path))


async def main():
    browser = await launch({
        'headless': False,
    })
    file_path = '/tmp/文件名' #文件存儲路徑,也要用來檢測是否下載成功,建議獨一無二的下載路徑,防止起衝突
    page = await browser.newPage()
    cdp = await page.target.createCDPSession()
    await cdp.send('Page.setDownloadBehavior', {'behavior': 'allow', 'downloadPath': file_path})#設置下載路徑
    try:
        await page.goto('文件下載路徑')#這一塊主要打開文件下載url會讓頁面關閉,加了try
    except:
        pass
    await asyncio.sleep(5)
    print('下載完畢') if check_file(file_path) else print("下載失敗") 
    await browser.close()


asyncio.get_event_loop().run_until_complete(main())
相關文章
相關標籤/搜索