简体   繁体   English

Puppeteer 标识符字符串变量不会解析; 不确定为什么

[英]Puppeteer identifier string variable won't parse; Unsure why

I'm trying to have a string be used inside a puppeteer string, it won't work for some reason.我正在尝试在 puppeteer 字符串中使用字符串,但由于某种原因它不起作用。

Specifically with this code具体使用此代码

await page.waitForSelector('div[class = "sh-dlr__list-result"')

When i try to parse in a variable当我尝试解析变量时

let identified1 = 'div[class = "sh-dlr__list-result"'

so making所以制作

await page.waitForSelector(identified1)

It won't work.它行不通。 This is really limiting, is there a way around this issue?这真的是有限的,有没有办法解决这个问题?

This is the expanded code这是扩展代码

https://jsfiddle.net/hewlbern/6p7kdozt/10/ Run it in your computer, jsfiddle unsure if I can run it from there. https://jsfiddle.net/hewlbern/6p7kdozt/10/在您的计算机上运行它,jsfiddle 不确定我是否可以从那里运行它。

I believe it is creating a cors error now - very weird: Why would using a variable create a cors error : /我相信它现在正在创建 cors 错误 - 非常奇怪:为什么使用变量会创建 cors 错误:/

Thanks!谢谢!

The reason is because you're declaring identified inside the page.evaluate() .原因是因为您在page.evaluate()中声明identified So, when you do the following it's already out of scope.因此,当您执行以下操作时,它已经超出了 scope。

if (currentPage < pagesToScrape) {
  console.log(identified1);
  await Promise.all([
    await page.click(buttonSelector),
    await page.waitForSelector(identified),
  ]);
}

You did log the identified1 but you're using identified for the selector.您确实记录了identified1 ,但您正在为选择器使用identified

You'll have to pass the identifier2 to the pageFunction like so:您必须像这样将identifier2传递给pageFunction

let newProducts = await page.evaluate(({ identifier2 }) => {
  // ...
},{ identifier2 });

See here some examples: 请参阅此处的一些示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM