使用正则表达式从Perl中的HTML中提取img标签

时间:2018-07-31 14:12:08

标签: html regex perl parsing

我需要从url中提取验证码,并用Tesseract识别出来。 我的代码是:

#!/usr/bin/perl -X
###
$user = 'user'; #Enter your username here
$pass = 'pass'; #Enter your password here
###
#Server settings
$home = "http://perltest.adavice.com";
$url = "$home/c/test.cgi?u=$user&p=$pass";
###Add code here!
#Grab img from HTML code
#if ($html =~ /<img. *?src. *?>/)
#{
#    $img1 = $1;
#}
#else 
#{
#    $img1 = "";
#}
$img2 = grep(/<img. *src=.*>/,$html);
if ($html =~ /\img[^>]* src=\"([^\"]*)\"[^>]*/)
{
    my $takeImg = $1;
    my @dirs = split('/', $takeImg);
    my $img = $dirs[2];
}
else
{
    print "Image not found\n";
}
###
die "<img> not found\n" if (!$img);
#Download image to server (save as: ocr_me.img)
print "GET '$img' > ocr_me.img\n";
system "GET '$img' > ocr_me.img";
###Add code here!
#Run OCR (using shell command tesseract) on img and save text as ocr_result.txt
system("tesseract ocr_me.img ocr_result");
print "GET '$txt' > ocr_result.txt\n";
system "GET '$txt' > ocr_result.txt";
###
die "ocr_result.txt not found\n" if (!-e "ocr_result.txt");
# check OCR results:
$txt = 'cat ocr_result.txt';
$txt =~ s/[^A-Za-z0-9\-_\.]+//sg;
$img =~ s/^.*\///;
print `echo -n "file=$img&text=$txt" | POST "$url"`;

如您所见,我正在尝试提取img src标签。该解决方案对我不起作用($ img1)use shell command tesseract in perl script to print a text output。我还使用了该解决方案的采用版本($ img2)How can I extract URL and link text from HTML in Perl?

如果您需要该页面的HTMLcode,则为:

<html>
<head>
<title>Perl test</title>
</head>
<body style="font: 18px Arial;">
<nobr>somenumbersimg src="/JJ822RCXHFC23OXONNHR.png" 
somenumbers<img src="/captcha/1533030599.png"/>
somenumbersimg src="/JJ822RCXHFC23OXONNHR.png" </nobr><br/><br/><form method="post" action="?u=user&p=pass">User: <input name="u"/><br/>PW: <input name="p"/><br/><input type="hidden" name="file" value="1533030599.png"/>Text: <input name="text"></br><input type="submit"></form><br/>
</body>
</html>

我收到找不到图片的错误。我的问题是我认为是错误的正则表达式。我无法安装任何模块,例如HTTP :: Parser或类似的

1 个答案:

答案 0 :(得分:4)

除了在HTML上使用正则表达式不是很可靠的事实之外,以下代码中的正则表达式也无法使用,因为它缺少捕获组,因此不会分配$1一个值。

if ($html =~ /<img. *?src. *?>/)
{
    $img = $1;
}

如果要使用正则表达式提取文本部分,则需要将该部分放在方括号中。例如:

$example = "hello world";
$example =~ /(hello) world/;

这会将$ 1设置为“ hello”。

正则表达式本身没有多大意义-在您有“。*?”的地方,它将匹配任何字符,后跟0或多个空格。那是“。*”的错字吗?可以匹配任意数量的字符,但不像“。*”那样贪婪,因此在找到正则表达式下一部分的匹配项时将停止。

此正则表达式可能更接近您要查找的内容。它将匹配第一个具有src属性的img标签,该标签以“ / captcha /”开头,并将图像URL存储在$1

$html =~ m%<img[^>]*src="(/captcha/[^"]*)"%s;

将其分解为工作原理。 “ m%....%”只是说“ /.../”的另一种方式,它使您可以在正则表达式中放入斜杠而不必将其转义。 “ [^>] *”将匹配零个或多个零号(“>”除外)中的任何字符-因此它将与标签的末尾不匹配。 “(// captcha / [^“] *)”正在使用捕获组来捕获双引号内将成为URL的所有内容。它还在末尾使用“ / s”修饰符来处理{{1} }好像只是一长行文本,并忽略其中可能不需要的任何$html,但是将img标签拆分为多行的机会仍然可以。

相关问题