2012-10-04 4 views
1

특정 데이터를 가져 오기 위해 특정 웹 사이트의 html 코드를 구문 분석하는 스크립트를 작성했습니다. 이 데이터를 가져 오는 두 개의 다른 사이트가 있으므로 elif 문을 사용합니다. 다음은 코드입니다."IndexError : 목록 색인이 범위를 벗어났습니다."elif 문

import urllib 

class city : 
    def __init__(self, city_name, link) : 
      self.name = city_name 
      self.url = link 
      self.high0 = 0 
      self.high1 = 0 
      self.high2 = 0 
      self.high3 = 0 
      self.high4 = 0 
      self.high5 = 0 
      self.high6 = 0 
      self.low0 = 0 
      self.low1 = 0 
      self.low2 = 0 
      self.low3 = 0 
      self.low4 = 0 
      self.low5 = 0 

    def retrieveTemps(self) : 
      filehandle = urllib.urlopen(self.url) 

      # get lines from result into array 
      lines = filehandle.readlines() 

      # (for each) loop through each line in lines 
      line_number = 0 # a counter for line number 
      for line in lines: 
        line_number = line_number + 1 # increment counter 

# find string, position otherwise position is -1 

        position1 = line.rfind('#f2') 
        if position1 > 0 : 
          self.high0 = lines[line_number].split('&')[0].split('>')[1] # next line: high 
          self.low0 = lines[line_number + 10].split('&')[0].split('>')[1] # next line:low 
        elif position1 < 0 : 
          position1 = line.rfind('>Overnight') 
          if position1 > 0 : 
            self.high0 = lines[line_number + 9].split('&')[0].split(':')[1] # next line: high 
            self.low0 = lines[line_number + 15].split('&')[0].split(':')[1] # next line:low 

position1 = line.rfind ('# f2') 일 때 스크립트가 완벽하게 작동합니다. 그러나 '# f2'(두 번째 사이트가 아닌 첫 번째 사이트의 html 코드에만 있습니다)를 찾을 수 없으면 '밤>'을 찾은 다음 그 사이에 데이터를 추출하도록 지시하려고합니다. ':'및 '&'. '데이터'는 항상 하나의 숫자입니다. 한 가지 문제가 추출하려고하는이 번호의 양쪽에 공백이있을 수 있다고 생각하지만이 문제를 해결하는 방법을 모르겠습니다.

self.high0 = 라인 [LINE_NUMBER + 9] .split ('&') [0] .split : 나는 스크립트를 실행하면 나는 오류 (':') [1] # 다음 줄을 : 높은 참고로

"IndexError 범위를 벗어리스트 인덱스는"여기에 내가 처음 웹 사이트 분석하고있는 HTML 코드입니다 :

</h3><img src="/weathericons/15.gif" longdesc="#f2" alt="Rain mixed with snow" title="Rain mixed with snow" /><ul> 
       <li class="high" title="High">3&deg;C</li> 
       <li class="low">&nbsp;</li> 
       <li class="pop">&nbsp;</li> 
      </ul> 
      </div> 

두 번째 웹 사이트에서 (사람이있는 나는를 수신하고

오류) :

<p class="txt-ctr-caps">Overnight<br><br></p> 
      <p><img src="/images/wtf/medium/nra60.png" width="86" height="86" alt="Rain Likely Chance for Measurable Precipitation 60%" title="Rain Likely Chance for Measurable Precipitation 60%" /></p> 
     <p>Rain<br>Likely<br></p> 
      <p class="point-forecast-icons-low">Low: 3 &deg;C</p> 
    </div> 
    <div class="one-ninth-first"> 
      <p class="txt-ctr-caps">Thursday<br><br></p> 
      <p><img src="/images/wtf/medium/ra70.png" width="86" height="86" alt="Rain Likely Chance for Measurable Precipitation 70%" title="Rain Likely Chance for Measurable Precipitation 70%" /></p> 
     <p>Rain<br>Likely<br></p> 
      <p class="point-forecast-icons-high">High: 9 &deg;C</p> 
    </div> 

도움을 주시면 고맙겠습니다. 감사합니다.

+2

소스 코드를 올바르게 포맷하십시오. http://www.crummy.com/software/BeautifulSoup/에서 HTML을 구문 분석하는 매우 쉽고 빠르며 휠을 다시 발명 할 필요가 없습니다. –

+1

I 이 사이트를 처음 접했고 소스를 올바르게 포맷했다고 생각 했습니까? – EverythingWX

+0

xml 파서를 사용하지 않는 이유가 있습니까? 따라서 코드를 수작업으로 작성하는 것보다 HTML을 파싱하는 것이 100 만 배나 쉽습니다. – ninMonkey

답변

3

이제 전체 코드를 제공 한 : 기본 인쇄 문으로 코드를 디버깅하는

def retrieveTemps(self) : 
     filehandle = urllib.urlopen(self.url) 
     lines = filehandle.read() # modified 

     position1 = lines.rfind('#f2') 
     if position1 > 0 : 
       self.high0 = lines[position1:].split('&')[0].split('>')[1] # next line: high 
       self.low0 = lines[position1+10:].split('&')[0].split('>')[1] # next line:low 
     elif position1 < 0 : 
       position1 = lines.rfind('>Overnight') 
       if position1 > 0 : 
         self.high0 = lines[position1+9:].split('&')[0].split(':')[1] # next line: high 
         self.low0 = lines[position1+15:].split('&')[0].split(':')[1] # next line:low 

그것도 doesn'e 도움말 시도에서 이것을 시도 회선 등의 변수와 선을에서 발생하는 어떤 거 처리 중입니다.

+0

답장을 보내 주셔서 감사합니다. 일단 변경하면 다음과 같은 오류가 발생합니다. AttributeError : 'list'객체에 'split'속성이 없습니다. – EverythingWX

+0

ok, lines = ?? 귀하의 프로그램에서. 나는 그 html 출력을 붙여 넣는 것 같아요. –

+1

죄송합니다. 제 원래 게시물에 모든 코드를 포함시켜야했습니다. 소스 코드를 업데이트했습니다. 그게 도움이 되니? – EverythingWX

관련 문제