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

如何使用Cheerio获取profileBackground的background-image链接

如何用Cheerio获取Anime-Planet用户的横幅背景图链接

你的问题出在只选中了profileBackground元素,但没有从它的style属性里提取background-image的链接。以下是修正方案:

问题分析

原代码仅定位到了目标元素,但没有解析元素的style属性——横幅背景图的链接是内嵌在这个属性的background-image值里的,而非元素本身的内容或其他属性。

修正后的代码

async function Al() {
  const cheerio = require("cheerio");
  const url = "https://www.anime-planet.com/users/kyoyacchi";
  const {data} = await client.axios.get(url, {
    headers: {
      "User-Agent":
        "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36",
    },
  });
  const $ = cheerio.load(data);

  // 定位到profileBackground元素,获取它的style属性
  const styleAttr = $(".pull-beta.pull-alpha.pullup.editableBanner")
    .find(".wrapper")
    .find("profileBackground")
    .attr("style");

  // 用正则提取background-image里的URL
  const bgImageMatch = styleAttr.match(/background-image:\s*url\(["']?(.*?)["']?\)/);
  let bgImageUrl = null;
  if (bgImageMatch && bgImageMatch[1]) {
    bgImageUrl = bgImageMatch[1];
    // 如果是相对路径,拼接成完整URL
    if (!bgImageUrl.startsWith('http')) {
      bgImageUrl = `https://www.anime-planet.com${bgImageUrl}`;
    }
  }

  return bgImageUrl;
}
Al();

关键步骤说明

  • 获取style属性:通过attr("style")拿到元素的内嵌样式字符串
  • 正则提取URL:用正则表达式匹配background-image: url("xxx")格式的内容,捕获其中的链接部分
  • 处理相对路径:Anime-Planet的背景图可能返回相对路径,需要拼接网站域名转为完整URL

内容的提问来源于stack exchange,提问作者Kyoya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:05:22