2014-09-21 2 views
4

데이터를 추출하려는 html 페이지의 소스 코드입니다.파이썬을 사용하여 테이블의 모든 행을 반복합니다. lxml xpath

웹 페이지 : http://gbgfotboll.se/information/?scr=table&ftid=51168 표는 페이지 하단에 있습니다

 <html> 
       <table class="clCommonGrid" cellspacing="0"> 
         <thead> 
          <tr> 
           <td colspan="3">Kommande matcher</td> 
          </tr> 
          <tr> 
           <th style="width:1%;">Tid</th> 
           <th style="width:69%;">Match</th> 
           <th style="width:30%;">Arena</th> 
          </tr> 
         </thead> 

         <tbody class="clGrid"> 

        <tr class="clTrOdd"> 
         <td nowrap="nowrap" class="no-line-through"> 
          <span class="matchTid"><span>2014-09-26<!-- br ok --> 19:30</span></span> 



         </td> 
         <td><a href="?scr=result&amp;fmid=2669197">Guldhedens IK - IF Warta</a></td> 
         <td><a href="?scr=venue&amp;faid=847">Guldheden Södra 1 Konstgräs</a> </td> 
        </tr> 

        <tr class="clTrEven"> 
         <td nowrap="nowrap" class="no-line-through"> 
          <span class="matchTid"><span>2014-09-26<!-- br ok --> 13:00</span></span> 



         </td> 
         <td><a href="?scr=result&amp;fmid=2669176">Romelanda UF - IK Virgo</a></td> 
         <td><a href="?scr=venue&amp;faid=941">Romevi 1 Gräs</a> </td> 
        </tr> 

        <tr class="clTrOdd"> 
        <td nowrap="nowrap" class="no-line-through"> 
         <span class="matchTid"><span>2014-09-27<!-- br ok --> 13:00</span></span> 



        </td> 
        <td><a href="?scr=result&amp;fmid=2669167">Kode IF - IK Kongahälla</a></td> 
        <td><a href="?scr=venue&amp;faid=912">Kode IP 1 Gräs</a> </td> 
       </tr> 

       <tr class="clTrEven"> 
        <td nowrap="nowrap" class="no-line-through"> 
         <span class="matchTid"><span>2014-09-27<!-- br ok --> 14:00</span></span> 



        </td> 
        <td><a href="?scr=result&amp;fmid=2669147">Floda BoIF - Partille IF FK </a></td> 
        <td><a href="?scr=venue&amp;faid=218">Flodala IP 1</a> </td> 
       </tr> 


         </tbody> 
       </table> 
     </html> 

지금 내가 사실은 내가 원하는 결과를 생성 코드를 ...이

import lxml.html 
url = "http://gbgfotboll.se/information/?scr=table&ftid=51168" 
html = lxml.html.parse(url) 
for i in range(12): 
    xpath1 = ".//*[@id='content-primary']/table[3]/tbody/tr[%d]/td[1]/span/span//text()" %(i+1) 
    xpath2 = ".//*[@id='content-primary']/table[3]/tbody/tr[%d]/td[2]/a/text()" %(i+1) 
    time = html.xpath(xpath1)[1] 
    date = html.xpath(xpath1)[0] 
    teamName = html.xpath(xpath2)[0] 
    if date == '2014-09-27': 
     print time, teamName 

이 결과를 제공합니다 :

13:00 Romelanda UF - IK 처녀 자리

13:00 0 KODE IF - IK Kongahälla

14시 Floda BoIF - Partille IF FK 이제 질문에

. 범위와 함께 for 루프를 사용하고 싶지 않습니다. 안정성이 없기 때문에 행이 테이블에서 변경 될 수 있고 범위를 벗어나면 충돌이 발생합니다. 그래서 제 질문은 제가 안전하게 여기에서 반복 할 수있는 방법입니다. 의미는 테이블에서 사용할 수있는 모든 행을 반복합니다. 그 이상도 이하도 아닌. 또한 코드를 더 좋게/빨리 만드는 다른 제안이 있으면 계속하십시오.

답변

3

다음 코드는 행의 수를 변경하지 않고 반복합니다. rows_xpath는 대상 날짜를 직접 필터링합니다. xpath는 for 루프 외부에서 한 번 만들어 지므로 더 빨라야합니다.

import lxml.html 
from lxml.etree import XPath 
url = "http://gbgfotboll.se/information/?scr=table&ftid=51168" 
date = '2014-09-27' 

rows_xpath = XPath("//*[@id='content-primary']/table[3]/tbody/tr[td[1]/span/span//text()='%s']" % (date)) 
time_xpath = XPath("td[1]/span/span//text()[2]") 
team_xpath = XPath("td[2]/a/text()") 

html = lxml.html.parse(url) 

for row in rows_xpath(html): 
    time = time_xpath(row)[0].strip() 
    team = team_xpath(row)[0] 
    print time, team 
+0

나는이 훌륭한 코드를 주셔서 감사합니다. 이게 어떻게 작동합니까? Stackoverlow를 처음 접했을 때 나는 당신이 나에게 제공 한 자신의 질문에 대해 자신의 질문에 답을 했습니까? 아니면이 답변을 작성 했으니까요? 또한 .strip()은 여기서 무엇을합니까? 나는 그것없이 그것을 달리고 동일한 결과를 얻으려고했기 때문에 다시 한번 감사드립니다 !! @Georges Martin –

+0

:-) 내 대답의 왼쪽에 체크 표시가 나타납니다. 내 대답이 당신에게 어울리면 그냥 클릭하십시오 ... –

+0

Ok thats great :), 빠른 질문 하나. .strip() 메소드는 무엇을 하는가? 내가 그것없이 실행하려고했기 때문에 나는 같은 결과를 얻었습니까? @Georges Martin –

관련 문제