2011-02-28 4 views
0

Python 및 BeautifulSoup에 새로운이 웹 사이트에서 경주 세부 정보를 긁어 내 로컬 클럽 웹 사이트에 표시하려고합니다. 로컬 사이트에 표시하기 위해 원격 사이트의 세부 정보를 긁어내는

가 여기에 지금까지 내 코드입니다 :

import urllib2 
import sys 
import os 

sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) 
from BeautifulSoup import BeautifulSoup 

# Road 
#cyclelab_url='http://www.cyclelab.com/OnLine%20Entries.aspx?type=Road%20Events' 

# MTB 
cyclelab_url='http://www.cyclelab.com/OnLine%20Entries.aspx?type=Mountain%20Biking%20Events' 

response = urllib2.urlopen(cyclelab_url) 
html = response.read() 

soup = BeautifulSoup(html) 
event_names = soup.findAll(attrs= {"class" : "SpanEventName"}) 
for event in event_names: 
    txt = event.find(text=True) 
    print txt 

event_details = soup.findAll(attrs= {"class" : "TDText"}) 
for detail in event_details: 
    lines=[] 
    txt_details = detail.find(text=True) 
    print txt_details 

이 이벤트 이름과 이벤트 세부 사항을 인쇄, 무엇을 내가 원하는, 해당 이벤트에 대한 이벤트 세부 정보를 이벤트 이름을 인쇄 한 다음 그 아래에. 그것은해야 할 것처럼 보일 것 같지만 나는 혼란 스럽다.

답변

0

업데이트 : Mark Longair가 정확하고/좋은 답변을 가지고 있습니다. 의견보기.

코드는 위에서 아래로 실행됩니다. 따라서 코드에서 먼저 모든 이벤트가 인쇄 된 다음 세부 사항이 인쇄됩니다. 코드를 함께 짜 맞춰야합니다. 즉, 모든 이벤트에 대해 세부 사항을 모두 인쇄 한 다음 다음 이벤트로 이동하십시오. 다음과 같이 시도하십시오.

[....] 
event_names = soup.findAll(attrs= {"class" : "SpanEventName"}) 
event_details = soup.findAll(attrs= {"class" : "TDText"}) 
for event in event_names: 
     txt = event.find(text=True) 
     print txt 
    for detail in event_details: 
     txt_details = detail.find(text=True) 
     print txt_details 

일부 개선 사항 : .strip()을 사용하여 공백과 개행을 모두 제거 할 수 있습니다. 예 : text_details = detail.find(text=True).strip().

+0

하고, * 모든 이벤트에 대한 세부 사항 - 나는 그것이 @ user621024가 원하는 것이 아니라고 생각합니다 ... –

+1

당신 말이 맞습니다. 나는 다른 것들과 시험하지 않고 서둘러 질문에 대답해서는 안된다. 당신의 대답을 Upvoted. – dermatthias

4

페이지의 구조를 보면 첫 번째 루프에서 찾은 이벤트 이름이 표의 행에 셀 쌍으로 다른 유용한 세부 정보가 모두 포함 된 테이블로 묶여 있음을 알 수 있습니다 . 그래서, 내가 할 수있는 것은 단지 하나의 루프가 있고, 이벤트 이름을 찾을 때마다 엔 클로징 테이블을 찾아 그 아래의 모든 이벤트를 찾으십시오. 이것은 작동하는 것 같다 OK :

soup = BeautifulSoup(html) 
event_names = soup.findAll(attrs= {"class" : "SpanEventName"}) 
for event in event_names: 
    txt = event.find(text=True) 
    print "Event name: "+txt.strip() 
    # Find each parent in turn until we find the table that encloses 
    # the event details: 
    parent = event.parent 
    while parent and parent.name != "table": 
     parent = parent.parent 
    if not parent: 
     raise Exception, "Failed to find a <table> enclosing the event" 
    # Now parent is the table element, so look for every 
    # row under that table, and then the cells under that: 
    for row in parent.findAll('tr'): 
     cells = row.findAll('td') 
     # We only care about the rows where there is a multiple of two 
     # cells, since these are the key/value pairs: 
     if len(cells) % 2 != 0: 
      continue 
     for i in xrange(0,len(cells),2): 
      key_text = cells[i].find(text=True) 
      value_text = cells[i+1].find(text=True) 
      if key_text and value_text: 
       print " Key:",key_text.strip() 
       print " Value:",value_text.strip() 

출력은 보이는 같은 : 다음 등

Event name: Columbia Grape Escape 2011 
    Key: Category: 
    Value: Mountain Biking Events 
    Key: Event Date: 
    Value: 4 March 2011 to 6 March 2011 
    Key: Entries Close: 
    Value: 31 January 2011 at 23:00 
    Key: Venue: 
    Value: Eden on the Bay, Blouberg 
    Key: Province: 
    Value: Western Cape 
    Key: Distance: 
    Value: 3 Day, 3 Stage Race (228km) 
    Key: Starting Time: 
    Value: -1:-1 
    Key: Timed By: 
    Value: RaceTec 
Event name: Investpro MTB Race 2011 
    Key: Category: 
    Value: Mountain Biking Events 
    Key: Event Date: 
    Value: 5 March 2011 
    Key: Entries Close: 
    Value: 25 February 2011 at 23:00 

...

이벤트 이름을 인쇄 할 페이지의 각 이벤트에 대해
+0

감사합니다 !! 그것은 잘 작동합니다! bautifulsoup에 대한 자습서 수보다이 의견에서 더 많은 것을 배웠습니다! – daemonza

관련 문제