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

如何用JavaScript从URL获取图片并下载维基百科文件页图片

解决维基百科文件页面图片下载问题

你当前生成的是维基百科的文件描述页面链接,并非直接的图片资源地址,所以需要先从该页面中提取出实际的图片URL,再执行下载操作。以下分两种常见运行场景给出实现方案:

浏览器端实现(前端网页环境)

通过动态请求页面、解析DOM获取图片链接,再触发浏览器下载:

async function downloadWikiImage(cityName) {
  const imagePageUrl = `https://tr.wikipedia.org/wiki/Dosya:${cityName}.jpg`;
  
  // 请求文件描述页面
  const response = await fetch(imagePageUrl);
  const html = await response.text();
  
  // 解析HTML找到目标图片元素
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  const imgElement = doc.querySelector('img.mw-file-element');
  if (!imgElement) {
    console.error('未找到对应图片');
    return;
  }
  
  // 处理缩略图URL为原图链接
  let imageSrc = imgElement.src;
  // 移除维基缩略图URL末尾的尺寸参数,获取原图地址
  imageSrc = imageSrc.replace(/\/\d+px-.+\.jpg$/, '.jpg');
  
  // 创建下载链接并触发下载
  const a = document.createElement('a');
  a.href = imageSrc;
  a.download = `${cityName}.jpg`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// 调用示例
downloadWikiImage('england');

Node.js端实现(后端脚本环境)

使用axios请求页面、cheerio解析DOM,结合https和fs完成图片下载:

  1. 先安装依赖:
npm install axios cheerio
  1. 实现代码:
const axios = require('axios');
const cheerio = require('cheerio');
const https = require('https');
const fs = require('fs');

async function downloadWikiImage(cityName) {
  const imagePageUrl = `https://tr.wikipedia.org/wiki/Dosya:${cityName}.jpg`;
  
  try {
    // 请求文件页面
    const { data: html } = await axios.get(imagePageUrl);
    const $ = cheerio.load(html);
    
    // 提取图片链接
    const imgSrc = $('img.mw-file-element').attr('src');
    if (!imgSrc) {
      console.error('未找到对应图片');
      return;
    }
    
    // 转换为原图链接
    const originalImgUrl = imgSrc.replace(/\/\d+px-.+\.jpg$/, '.jpg');
    
    // 下载图片到本地
    const fileStream = fs.createWriteStream(`${cityName}.jpg`);
    https.get(originalImgUrl, (response) => {
      response.pipe(fileStream);
      fileStream.on('finish', () => {
        fileStream.close();
        console.log(`图片已下载:${cityName}.jpg`);
      });
    }).on('error', (err) => {
      fs.unlink(`${cityName}.jpg`, () => {}); // 删除未完成的文件
      console.error('下载失败:', err.message);
    });
  } catch (err) {
    console.error('请求页面失败:', err.message);
  }
}

// 调用示例
downloadWikiImage('england');

注意事项

  • 维基百科图片受版权保护,下载前请确认符合使用规范
  • 部分图片可能无原图权限或页面不存在,需做好错误处理
  • 频繁请求可能触发反爬机制,建议添加请求间隔

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:30:54