我正在使用名为 selenium-webdriver 的 node.js 包以及 Raspberry Pi (Raspbian Stretch) 上的 Firefox v52.9.0。
在某个时刻,我想执行相当于 Firefox GUI“页面另存为”功能的功能。
我在 this page 上找到了类似内容的引用:
# Write the output to output.txt
with open('output.txt', 'w') as file:
file.write(str(browser.page_source))
这里的问题是本指南使用 python 而不是 Node。我不确定如何实现等效的代码。
我找到了this在文档中,但文档不包含任何示例代码,我不确定如何实现 .write
函数。谁能解释一下(或给我指出一个资源以供理解)如何在 selenium-webdriver 中实现“保存文件”功能?
还值得一提的是,我需要保存的文件包含一些 AJAX 和 Javascript 对 DOM 所做的修改 - 简单地保存 html 文档的原始源代码是 Not Acceptable ,但它需要代表页面的当前状态。
这里是一些上下文代码:
const {Builder, By, Key, until} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
await driver.get('http://localhost/mypage.html');
await driver.sleep(10000);
/*SOMEHOW SAVE THE PAGE TO A FILE */
} finally {
await driver.quit();
}
})();
最佳答案
只需调用driver.getPageSource()
try {
await driver.get('https://google.com');
await driver.sleep(1000);
const source = await driver.getPageSource();
fs.writeFileSync('source.html', source);
} finally {
await driver.quit();
}
关于node.js - Node js selenium-webdriver 将页面另存为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51238317/