【发布时间】:2018-07-30 14:58:36
【问题描述】:
对于特定用例,我很难使用 puppeteer 导航相对 url。您可以在下面看到基本设置和描述问题的伪示例。
基本上我想更改浏览器认为他所在的当前网址。
我已经尝试过的:
- 通过自己解析所有相关 URL 来操作响应正文。与一些基于 javascript 的链接发生冲突。
- 如果请求 url 与响应 url 不匹配,则触发新 page.goto(response.url) 并返回上一个请求的响应。好像不能输入自定义选项,所以不知道哪个请求是假page.goto。
有人可以帮我一把吗?提前致谢。
设置:
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”时,您是想重定向到不同的 URL,还是只是想 replace the state 欺骗浏览器?另外,你能添加你的
fetch函数的来源吗? -
我试图替换状态。不幸的是 replaceState() 不起作用,因为它只适用于相同的来源。但我可以直接更改位置。感谢@GrantMiller 为我指明了正确的方向。
标签: javascript web-scraping puppeteer