You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用axios与jsdom获取CGV网站a标签href和img资源及代码修复

代码修改点

  • 原代码中getElementsByClassName返回的是DOM元素集合,无法直接调用querySelectorAll,需要先取第一个匹配的容器节点再执行子节点查询
  • 遍历得到的li节点本身就支持DOM查询方法,不需要访问不存在的document属性
  • 补充了分别提取a标签href属性、img标签资源地址与说明文本的逻辑

修复后可运行代码

const { default: axios } = require("axios");
const { JSDOM } = require("jsdom");

(async () => {
    try {
        const { data } = await axios.get(
          "https://www.cgv.id/en/movies/now_playing"
        );
        const doc = new JSDOM(data).window.document;
        // 获取电影列表容器节点
        const movieListBody = doc.getElementsByClassName('movie-list-body')[0];
        // 取所有电影项li节点
        const movieItems = [...movieListBody.querySelectorAll('li')];
        // 遍历提取目标字段
        const result = movieItems.map(li => {
            const aNode = li.querySelector('a[href]');
            const imgNode = li.querySelector('img');
            return {
                // a标签的href属性
                movieDetailLink: aNode ? aNode.getAttribute('href') : '',
                // img标签的图片资源地址
                moviePosterSrc: imgNode ? imgNode.getAttribute('src') : '',
                // img标签的alt说明文本
                moviePosterAlt: imgNode ? imgNode.getAttribute('alt').trim() : ''
            }
        })
        console.log(result);
    } catch (error) {
        console.log('运行出错:', error);
    }
})()

运行后会输出包含每部电影详情页链接、海报资源地址、海报说明文本的结构化数组。

内容的提问来源于stack exchange,提问作者lian abdiansyah tanjung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:36:04