我最近开始在JavaScript中尝试使用Puppeteer进行网络抓取,并注意到当我使用无头Puppeteer实例运行代码时,它不会返回我正在寻找的标签,而是返回[]
。但是,当关闭无头模式时,代码可以很好地返回标签。它返回的标签是
[ ElementHandle {
_context:
ExecutionContext { _client: [CDPSession], _world: [DOMWorld], _contextId: 3 },
_client:
CDPSession {
_events: [Object],
_eventsCount: 27,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '6950CA7711045DA500204C2EFDAFC5B3' },
_remoteObject:
{ type: 'object',
subtype: 'node',
className: 'HTMLHeadingElement',
description: 'h1',
objectId: '{"injectedScriptId":3,"id":3}' },
_disposed: false,
_page:
Page {
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
_closed: false,
_client: [CDPSession],
_target: [Target],
_keyboard: [Keyboard],
_mouse: [Mouse],
_timeoutSettings: [TimeoutSettings],
_touchscreen: [Touchscreen],
_accessibility: [Accessibility],
_networkManager: [NetworkManager],
_frameManager: [FrameManager],
_emulationManager: [EmulationManager],
_tracing: [Tracing],
_pageBindings: Map {},
_ignoreHTTPSErrors: false,
_coverage: [Coverage],
_javascriptEnabled: true,
_viewport: [Object],
_screenshotTaskQueue: [TaskQueue],
_workers: Map {} },
_frameManager:
FrameManager {
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_client: [CDPSession],
_page: [Page],
_networkManager: [NetworkManager],
_timeoutSettings: [TimeoutSettings],
_frames: [Map],
_contextIdToContext: [Map],
_isolatedWorlds: [Set],
_mainFrame: [Frame] } } ]
我尝试使用await page.goto(url, {"waitUntil" : "networkidle0"});
来使程序等到页面完全加载后再返回标记,但还是没有运气。这是我的功能异常的代码:
const initializeBrowserTask = async (proxy) => {
console.log("Initializing browser task...");
if (proxy == '') {
console.log('No proxy.')
const browser = await puppeteer.launch({ headless: false });
return browser;
} else {
const browser = await puppeteer.launch({
'args': ['--proxy-server=`${proxy}`']
});
console.log("Proxy: `${proxy}`")
return browser;
};
}
const browserTask = async (proxy, url) => {
const browser = await initializeBrowserTask(proxy);
let check = 0
const page = await browser.newPage();
console.log('Running...')
await page.goto(url);
console.log("Arrived at URL!")
let status = await page.$x('//*[@id="app"]/div[1]/div/div[1]/h1');
console.log(status)
};
browserTask('', 'http://adidas.com/yeezy')
我确实删除了{"waitUntil" : "networkidle0"}
,因为它不能解决问题。由于某种原因,此代码在浏览器不是无头的情况下将起作用,但在浏览器不是无头的情况下将返回[]
。为什么会出现此问题,我该如何解决?
答案 0 :(得分:0)
只需弄清楚我的代码出了什么问题。显然,我尝试抓取的网站(adidas.com)会根据标头过滤掉请求。我没有意识到的是,在无头模式下,我实际上到达了Adidas的403 Access Denied页面,这就是为什么我要查找的标签不存在的原因。我猜无头木偶只是发送HTTP请求的另一种方式,而无头无人驾驶更像是实际的网络驱动程序,这就是为什么无头无人驾驶模式没有被阿迪达斯阻止的原因。
要修复无头模式并添加适当的标题,我在“ page.goto(url);”之前使用了这一行代码行:
await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36');
事实证明,我所缺少的只是使Adidas网站无法阻止我的标题。