使用JavaScript书签从图像链接中提取alt文本

时间:2015-11-06 12:59:13

标签: javascript html regex perl alt

我找到了一种通过我找到的Perl脚本从图像链接中提取alt文本的方法。但是,该方法需要下载目标HTML;通过Perl脚本处理它,然后生成一个带有我需要的特定alt文本的文本文件;然后删除一些额外的文本,我无法通过代码手动过滤掉,因为我不知道如何使用Perl使用正则表达式(我尝试安装PCRE无效)。

这种方法仍然不切实际,我确信我可以更快,更快地通过JavaScript书签提取alt文本,并立即将输出整齐地列在新标签中。但是,我不知道如何将我拥有的Perl脚本转换为JavaScript,也不知道如何从头开始编写。

这是Perl脚本:

{
    # Get data from HTML file
    my $From = cwd() . '/' . $ARGV[0];
    open( HTMLFILE, '<' . $From ) or die( "Cannot open $From to read." );

    my $Html;
    read HTMLFILE, $Html, -s $From;
    close HTMLFILE;

    # Find IMG elements
    print "Images found!";
    my %AltTexts;
    while ( $Html =~ /(<IMG\b.*?>)/isg ) {
        my $ImgElement = $1;

        # Find SRC tag
        $ImgElement =~ /SRC\s*=\s*([\"\'])(.*?)\1/is;
        my $Src = $2;

        # Find ALT tag & store text
        if ( $ImgElement =~ /ALT\s*=\s*([\"\'])(.*?)\1/is ) {
            $AltTexts{$Src} = $2;
        }
        else {    # No ALT found so give it default text if none already found
            unless ( exists( $AltTexts{$Src} ) ) {
                $AltTexts{$Src} = 'NO_ALT_TEXT';
            }
        }
    }

    # Write extracted data to a file
    my $To = cwd() . '/' . $ARGV[0] . '.txt';
    open( ALTTEXTFILE, '>' . $To ) or die( "Cannot open $To to write." );

    foreach my $SrcPath ( sort keys %AltTexts ) {
        print ALTTEXTFILE "$AltTexts{$SrcPath}\n";
    }
    close ALTTEXTFILE;
}

我做了调整以阻止脚本打印链接,删除空白行等

可以找到原始脚本here

所以,我的问题是用于提取替代文字的JavaScript是什么样的?

1 个答案:

答案 0 :(得分:2)

像这样:

javascript:(function() {
  var imgs = document.images,alts=[];
  for (var i=0;i<imgs.length;i++) {
      alts.push(imgs[i].getAttribute("alt") || "no alt");
  }
  alert(alts.join("\n"));
})()

示例代码:

(function() {
  var imgs = document.images,alts=[];
  for (var i=0;i<imgs.length;i++) {
    alts.push(imgs[i].getAttribute("alt") || "no alt");
  }
  console.log(alts);
})()
<img alt="alt1" />
<img alt="" />
<img alt="alt2" />

在新窗口中显示(弹出窗口拦截器允许)

javascript:(function() {
  var imgs = document.images,alts=[],w;
  for (var i=0;i<imgs.length;i++) {
    alts.push(imgs[i].getAttribute("alt") || "no alt");
  }
  if (alts.length>0) {
    w = window.open("","_blank");
    if (w) {
      w.document.write(alts.join("<br />"));
      w.document.close();
    }
    else {
      alert("cannot pop\n"+alts.join("\n"));
    }
  }
})()

为避免重复:

变化

alts.push(imgs[i].getAttribute("alt") || "no alt");

var alt = imgs[i].getAttribute("alt");
if (alts && alts.indexOf(alt)==-1) alts.push(alt);