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

Scrapy中如何跳过缺失数据?为网页笑话匹配对应链接

解决方案:匹配笑话与对应链接

没问题,我来帮你搞定这个笑话和链接的匹配需求!针对你给出的HTML结构,我们可以用原生JavaScript(或jQuery)来逐个匹配笑话元素和对应的链接,同时处理没有链接的情况。

原生JavaScript实现

下面是完整的代码示例,注释里写清了每一步的逻辑:

// 获取所有包含笑话文本的.hehe元素
const jokeElements = document.querySelectorAll('.hehe');

// 遍历每个笑话元素
jokeElements.forEach(jokeEl => {
  // 提取笑话的名称(比如"joke23")
  const jokeName = jokeEl.querySelector('span').textContent.trim();
  
  // 查找对应的链接:href中包含当前笑话名称的.hrtojoke元素
  // 如果你的href格式是严格的"link/to/jokeXX",可以用[href$="/${jokeName}"]更精确匹配
  const correspondingLink = document.querySelector(`.hrtojoke[href*="${jokeName}"]`);
  
  if (correspondingLink) {
    // 匹配到链接的处理:把笑话变成可点击的跳转元素
    jokeEl.style.cursor = 'pointer';
    jokeEl.addEventListener('click', () => {
      window.location.href = correspondingLink.href;
    });
    console.log(`✅ 找到${jokeName}的链接:${correspondingLink.href}`);
  } else {
    // 未匹配到链接的处理:添加视觉提示
    jokeEl.style.color = '#999';
    jokeEl.title = '该笑话暂无链接';
    console.log(`❌ ${jokeName}没有对应的链接`);
  }
});

jQuery实现(如果项目已引入jQuery)

如果你的项目已经用了jQuery,代码会更简洁:

$('.hehe').each(function() {
  const jokeName = $(this).find('span').text().trim();
  // 查找对应链接
  const $targetLink = $('.hrtojoke[href*="' + jokeName + '"]');
  
  if ($targetLink.length > 0) {
    // 绑定跳转事件
    $(this).css('cursor', 'pointer').on('click', function() {
      window.location.href = $targetLink.attr('href');
    });
  } else {
    // 标记无链接状态
    $(this).css('color', '#999').attr('title', '暂无链接');
  }
});

关键逻辑说明

  • 匹配规则:通过[href*="${jokeName}"]属性选择器,筛选出href包含当前笑话名称的链接元素。如果你的链接格式是固定的link/to/jokeXX,可以改用[href$="/${jokeName}"](表示href以/jokeXX结尾),避免出现类似joke23和joke233的误匹配。
  • 自定义处理:你可以根据需求修改匹配到/未匹配到链接时的操作,比如给无链接的笑话添加特殊类名、插入提示文本,或者把链接直接插入到笑话元素内部等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:21:51