2012-04-06 9 views
0

나는 특정 태그에서 텍스트를 검색 할 수있는 조건이 있지만 true 반환하는 것 같지 않습니다? 어떤 도움이?왜이 조건이 작동하지 않습니까? Div 함께 클래스

#!/usr/bin/perl 

use HTML::TreeBuilder; 
use warnings; 
use strict; 
my $URL = "http://prospectus.ulster.ac.uk/modules/index/index/selCampus/JN/selProgramme/2132/hModuleCode/COM137"; 
my $tree = HTML::TreeBuilder->new_from_content($URL); 

if (my $div = $tree->look_down(_tag => "div ", class => "col col60 moduledetail")) { 
printf $div->as_text(); 
      print "test"; 
open (FILE, '>mytest.txt'); 
print FILE $div; 
close (FILE); 
} 
     print $tree->look_down(_tag => "th", class => "moduleCode")->as_text(); 
$tree->delete(); 

그것은 if 문으로 들어갈되지 않고 if 문 외부에 인쇄가 정의되지 않은 값이 있음을 말하고있다,하지만 난이 태그가 존재하기 때문에 그것이 사실 반환되어야한다는 것을 알고있다.

<th class="moduleCode">COM137<small>CRN: 33413</small></th> 

감사

+0

@downvoter :이 질문에 무엇이 잘못 되었습니까? – Borodin

답변

3

당신은 HTML::TreeBuilder->new_from_content를 호출 아직 콘텐츠 대신 URL을 공급하고 있습니다. 당신은 HTML::TreeBuilder에 그것을 보내기 전에 get HTML을 가지고 있어야합니다.

아마도 가장 간단한 방법은 get이라는 서브 루틴을 가져 오는 LWP::Simple을 사용하는 것입니다. 이렇게하면 URL의 데이터를 읽고 문자열로 반환합니다.

조건부 블록이 실행되지 않는 이유는 태그 이름에 공백이 있다는 것입니다. "div " 대신 "div"이 필요합니다.

은 또한 다음과 같은주의 :

  • 당신이해야하지 출력 형식 지정자로 해당 문자열로 printf를 사용하여 하나의 문자열. 경고가 누락되었습니다. 경고를 생성하고 문자열을 올바르게 출력하지 못할 수 있습니다.

  • 이상적으로는 어휘 파일 핸들과 3 인수 형식 인 open을 사용해야합니다. 또한 모든 open 통화 상태를 확인하고 그에 따라 응답해야합니다.

  • 스칼라 변수 $div은 축복받은 해시 참조이므로 그대로 인쇄하면 HTML::Element=HASH(0xfffffff)과 같은 결과가 출력됩니다. 당신은 내가 출력을 포맷하지 않은 있지만, 나는 당신이 원하는 것을 말할 수 없다, 당신이 이러한 오류와

이 코드는 다음과 같습니다 보정 표시 할 값을 추출하는 메서드를 호출해야합니다.

use strict; 
use warnings; 

use HTML::TreeBuilder; 
use LWP::Simple; 

my $url = "http://prospectus.ulster.ac.uk/modules/index/index/selCampus/JN/selProgramme/2132/hModuleCode/COM137"; 
my $html = get $url; 
my $tree = HTML::TreeBuilder->new_from_content($html); 

if (my $div = $tree->look_down(_tag => "div", class => "col col60 moduledetail")) { 
    print $div->as_text(), "\n"; 
    open my $fh, '>', 'mytest.txt' or die "Unable to open output file: $!"; 
    print $fh $div->as_text, "\n"; 
} 

print $tree->look_down(_tag => "th", class => "moduleCode")->as_text, "\n"; 
관련 문제