如何使用PhantomJS登录Web应用并完成区域截图与PDF转换?
Hey there! Let's work through your two PhantomJS requirements with actionable code and explanations. I'll make sure each example is easy to tweak for your specific web app.
1. Login to Web App & Capture Screenshots of Different Regions
First, we need to simulate the login process, wait for the app to load after authentication, then define specific regions to capture. PhantomJS lets us set a clipRect to target parts of the page—perfect for your need.
Here's a complete script:
var page = require('webpage').create(); var system = require('system'); // Helper function to wait for a specific condition (like element presence) function waitFor(testFx, onReady, timeOutMillis) { var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 30000, // Default 30s timeout start = new Date().getTime(), condition = false, interval = setInterval(function() { if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { // If not time-out yet and condition not fulfilled condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); } else { if(!condition) { // If condition still not fulfilled (timeout but condition is 'false') console.log("Timeout waiting for condition"); phantom.exit(1); } else { // Condition fulfilled (timeout and/or condition is 'true') typeof(onReady) === "string" ? eval(onReady) : onReady(); clearInterval(interval); // Stop this interval } } }, 250); // Check every 250ms } // Step 1: Open the login page page.open('https://your-web-app-login-url.com', function(status) { if (status !== 'success') { console.log('Failed to load login page'); phantom.exit(1); } // Step 2: Fill login form and submit page.evaluate(function() { // Replace with your actual form selectors document.getElementById('username').value = 'your-username'; document.getElementById('password').value = 'your-password'; document.getElementById('login-button').click(); }); // Step 3: Wait for post-login page to load (check for a unique element on dashboard) waitFor(function() { return page.evaluate(function() { return document.getElementById('dashboard-header') !== null; }); }, function() { console.log('Login successful! Now capturing screenshots...'); // Capture full page first (optional) page.render('full-dashboard.png'); // Capture specific region 1: e.g., user profile section page.clipRect = { top: 100, left: 20, width: 300, height: 200 }; page.render('user-profile.png'); // Capture specific region 2: e.g., analytics widget page.clipRect = { top: 100, left: 350, width: 400, height: 300 }; page.render('analytics-widget.png'); phantom.exit(); }); });
Key Notes:
- Replace
your-web-app-login-url.comand form selectors (username,password,login-button) with your app's actual values. - The
waitForfunction ensures we don't take screenshots before the post-login page is fully loaded—adjust the target element (dashboard-header) to something unique on your app's logged-in page. clipRectusestop/leftcoordinates (from the top-left corner of the page) pluswidth/heightto define the area to capture. You can inspect your page to get these values.
2. Login & Convert Page to PDF
For PDF conversion, the flow is similar (login first), then we set the paperSize property to define the PDF dimensions, then render to a PDF file.
Here's the script:
var page = require('webpage').create(); var system = require('system'); // Reuse the same waitFor helper from above function waitFor(testFx, onReady, timeOutMillis) { var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 30000, start = new Date().getTime(), condition = false, interval = setInterval(function() { if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); } else { if(!condition) { console.log("Timeout waiting for condition"); phantom.exit(1); } else { typeof(onReady) === "string" ? eval(onReady) : onReady(); clearInterval(interval); } } }, 250); } // Step 1: Open login page page.open('https://your-web-app-login-url.com', function(status) { if (status !== 'success') { console.log('Failed to load login page'); phantom.exit(1); } // Step 2: Submit login form page.evaluate(function() { document.getElementById('username').value = 'your-username'; document.getElementById('password').value = 'your-password'; document.getElementById('login-button').click(); }); // Step 3: Wait for logged-in page waitFor(function() { return page.evaluate(function() { return document.getElementById('dashboard-header') !== null; }); }, function() { console.log('Login successful! Converting page to PDF...'); // Set PDF paper size (options: A4, Letter, or custom dimensions) page.paperSize = { format: 'A4', orientation: 'portrait', margin: { top: '1cm', bottom: '1cm', left: '1cm', right: '1cm' } }; // Optional: If you need to convert a different page after login, navigate to it first // page.open('https://your-web-app-url.com/invoice', function() { // page.render('invoice.pdf'); // phantom.exit(); // }); // Convert current logged-in page to PDF page.render('dashboard.pdf'); console.log('PDF generated successfully!'); phantom.exit(); }); });
Key Notes:
- Adjust
paperSizeto match your needs: useformatfor standard sizes, or define customwidth/height(e.g.,width: '210mm', height: '297mm'for A4). - If you need to convert a specific page (like an invoice or report) instead of the dashboard, uncomment the
page.openblock inside the success handler to navigate to that URL first before rendering. - PhantomJS renders the PDF as it appears in the headless browser, so make sure your page's CSS is print-friendly if needed.
内容的提问来源于stack exchange,提问作者AMAN VYAS
相关产品推荐
相关产品推荐

