对于特定用例,我很难使用 puppeteer 导航相对 url。您可以在下面看到基本设置和描述问题的伪示例。
本质上,我想更改浏览器认为他所在的当前 url。
我已经尝试过的:
有人可以帮我一把吗?提前致谢。
设置:
const browser = await puppeteer.launch({
headless: false,
});
const [page] = await browser.pages();
await page.setRequestInterception(true);
page.on('request', (request) => {
const resourceType = request.resourceType();
if (['document', 'xhr', 'script'].includes(resourceType)) {
// fetching takes place on an different instance and handles redirects internally
const response = await fetch(request);
request.respond({
body: response.body,
statusCode: response.statusCode,
url: response.url // no effect
});
} else {
request.abort('aborted');
}
});
导航:
await page.goto('https://start.de');
// redirects to https://redirect.de
await page.click('a');
// relative href '/demo.html' resolves to https://start.de/demo.html instead of https://redirect.de/demo.html
await page.click('a');
更新 1
解决方案
通过 window.location 操作浏览器历史记录方向。
await page.goto('https://start.de');
// redirects to https://redirect.de internally
await page.click('a');
// changing current window location
await page.evaluate(() => {
window.location.href = 'https://redirect.de';
});
// correctly resolves to https://redirect.de/demo.html instead of https://start.de/demo.html
await page.click('a');
最佳答案
当您匹配要编辑其正文的请求时,只需获取 URL 并使用“node-fetch”或“request”模块进行调用,当您收到正文编辑然后将其作为对原始请求的响应发送.
例如:
const requestModule = require("request");
const cheerio = require("cheerio");
page.on("request", async (request) => {
// Match the url that you want
const isMatched = /page-12/.test(request.url());
if (isMatched) {
// Make a new call
requestModule({
url: request.url(),
resolveWithFullResponse: true,
})
.then((response) => {
const { body, headers, statusCode, statusMessage } = response;
const contentType = headers["content-type"];
// Edit body using cheerio module
const $ = cheerio.load(body);
$("a").each(function () {
$(this).attr("href", "/fake_pathname");
});
// Send response
request.respond({
ok: statusMessage === "OK",
status: statusCode,
contentType,
body: $.html(),
});
})
.catch(() => request.continue());
} else request.continue();
});
关于javascript - 在 Puppeteer 请求拦截期间手动更改响应 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51596858/