background
When NPM installs puppeteer, it will automatically install and download chromium. Because it cannot access the Internet or taobao source, there will always be error. Follow these steps to install puppeteer and Chromium correctly.
Unload Chromium when puppeteer is installed
npm i --save puppeteer --ignore-scripts
Copy the code
Or create a.npmrc file with the contents
puppeteer_skip_chromium_download = 1
Copy the code
Find the corresponding chromium in Puppeteer and download it
When downloading Chromium, you must install the version that corresponds to puppeteer, otherwise puppeteer will fail to start Chromium.
In node_modules/puppeteer – core/lib/BrowserFetcher js found in each platform Chrome download address. Where %s is replaced with the value of DEFAULT_DOWNLOAD_HOST and %d is replaced with the version number.
Find the version number in node_modules/puppeteer-core/ packes. json
Get the download address after replacement
Storage.googleapis.com/chromium-br…
Download it, unzip it, and put it in the project directory, which I put under Chrome.
Or directly download the corresponding version of Chromium from Taobao source. address
Copy Chromium to the project directory
Copy the decompressed files to the Chromium directory in the project root directory. Set the executablePath property (Chromium boot path) inside the Puppeteer launch.
const browser = await puppeteer.launch({
executablePath: 'D:/chromium/chrome.exe'
});
Copy the code
Finally, add chromium to.gitignore
UI automated testing encountered problems
If a page has an IFrame, you need to operate on the elements in the iframe. If the iframe is not fully loaded, you need to operate on the elements in the IFrame. Therefore, an error message is reported. So how do you know if iframe is loaded correctly?
/**
* Waits until the iframe is attached and then returns it to the caller
* @returns {object} The Puppeteer iframe element
*/
async function iframeAttached(page, nameOrId) {
return new Promise(async resolve => {
const pollingInterval = 1000;
const poll = setInterval(async function waitForIFrameToLoad() {
const iFrame = page.frames().find(frame => frame.name() === nameOrId);
if (iFrame) {
clearInterval(poll);
resolve(iFrame);
}
}, pollingInterval);
});
}
Copy the code
usage
const iframe = await iframeAttached(page, 'YOUR_IFRAME_NAME_OR_ID'); // You can now use the iframe iframe.doSomething(...) ;Copy the code