代码之家  ›  专栏  ›  技术社区  ›  Dmitriy Kisil

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

  •  0
  • Dmitriy Kisil  · 技术社区  · 8 年前

    我需要从url中提取captcha并用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 回复  |  直到 8 年前
        1
  •  4
  •   Chris Turner    8 年前

    $1

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

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

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

    $html \n