gpt4 book ai didi

javascript - puppeteer 网络抓取条件 if 语句

转载 作者:行者123 更新时间:2023-12-02 21:22:49 24 4
gpt4 key购买 nike

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

代码=>

enter image description here

输出=>

enter image description here

我尝试过执行以下操作

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 相同的输出

最佳答案

您检查未定义为时已晚:任何子级都可能是未定义,并使用索引此未定义 >[0] 会抛出错误。

如果您的 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';

关于javascript - puppeteer 网络抓取条件 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60807358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com