【问题标题】:puppeteer web scraping conditionals if statementpuppeteer web 抓取条件 if 语句
【发布时间】:2020-03-23 02:49:40
【问题描述】:

正在抓取表格... 每个国家/地区名称都在 <a> 标记内,但有些不是。当结构发生变化时,程序崩溃

代码 =>

输出 =>

我尝试过以下操作

const countryName = e.children[1].children[0].children[0].data || 'hello world'

它不起作用 但我也尝试过使用 IfStatement

const countryName = e.children[1].children[0].children[0].data
if (countryName === undefined) {
   countryName = 'hello world'
}

它也不起作用,同样的输出错误。

我知道错误是什么意思...我知道 HTML 结构不一样,但它不会读取我正在实施的条件,以赋予 countryName 变量其值

有什么想法吗?

PD:与cheeriojs 相同的输出

【问题讨论】:

    标签: javascript node.js web-scraping puppeteer cheerio


    【解决方案1】:

    您检查undefined 为时已晚:任何children 都可以是undefined,并且用[0] 索引此undefined 可能会引发错误。

    如果您的 Node.js (V8) 或转译支持 optional chainingnullish coalescing,您可以这样做:

    const countryName = e?.children?.[1]?.children?.[0]?.children?.[0]?.data ?? 'hello world';
    

    否则,你需要这个:

    const countryName =
      e &&
      e.children &&
      e.children[1] &&
      e.children[1].children &&
      e.children[1].children[0] &&
      e.children[1].children[0].children &&
      e.children[1].children[0].children[0] &&
      e.children[1].children[0].children[0].data ||
      'hello world';
    
    

    【讨论】:

      【解决方案2】:

      你可能想要这样的东西:

      $(e).find('a').first().text() || 'hello world'
      

      你几乎从不想诉诸于使用与 Cheerio 的孩子。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        相关资源
        最近更新 更多