2013-06-24 5 views
1

굵게 텍스트를 추출하고 싶습니다.이 웹 사이트는이 웹 사이트에서 최신 날씨 psi를 나타내는 것입니다. 누구든지이 코드를 사용하여 추출하는 방법을 알고 있습니까?python beautifulsoup 텍스트를 추출

또한 계산을하기 위해 현재 날씨 psi의 앞쪽에있는 두 개의 값을 추출해야했습니다. 총 값 3 개 (최신 및 이전 두 값)

예 : 현재 값 (굵은 글꼴)은 오전 5시 : 51이고, 또한 3AM 및 4AM이 필요합니다. 아무도 이것을 알고 나를 도와 줄 수 있습니까? 미리 감사드립니다!

from pprint import pprint 
    import urllib2 
    from bs4 import BeautifulSoup as soup 


    url = "http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours" 
    web_soup = soup(urllib2.urlopen(url)) 

    table = web_soup.find(name="div", attrs={'class': 'c1'}).find_all(name="div")[2].find_all('table')[0] 

    table_rows = [] 
    for row in table.find_all('tr'): 
     table_rows.append([td.text.strip() for td in row.find_all('td')]) 

    data = {} 
    for tr_index, tr in enumerate(table_rows): 
     if tr_index % 2 == 0: 
      for td_index, td in enumerate(tr): 
       data[td] = table_rows[tr_index + 1][td_index] 

    pprint(data) 

인쇄 :

{'10AM': '49', 
    '10PM': '-', 
    '11AM': '52', 
    '11PM': '-', 
    '12AM': '76', 
    '12PM': '54', 
    '1AM': '70', 
    '1PM': '59', 
    '2AM': '64', 
    '2PM': '65', 
    '3AM': '59', 
    '3PM': '72', 
    '4AM': '54', 
    '4PM': '79', 
    '5AM': '51', 
    '5PM': '82', 
    '6AM': '48', 
    '6PM': '79', 
    '7AM': '47', 
    '7PM': '-', 
    '8AM': '47', 
    '8PM': '-', 
    '9AM': '47', 
    '9PM': '-', 
    'Time': '3-hr PSI'} 

답변

1

여기에 무슨 일이 일어나고 있는지 이해하고 있는지 확인하십시오 :

import urllib2 
import datetime 

from bs4 import BeautifulSoup as soup 


url = "http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours" 
web_soup = soup(urllib2.urlopen(url)) 

table = web_soup.find(name="div", attrs={'class': 'c1'}).find_all(name="div")[2].find_all('table')[0] 

data = {} 
bold_time = '' 
cur_time = datetime.datetime.strptime("12AM", "%I%p") 
for tr_index, tr in enumerate(table.find_all('tr')): 
    if 'Time' in tr.text: 
     continue 
    for td_index, td in enumerate(tr.find_all('td')): 
     if not td_index: 
      continue 
     data[cur_time] = td.text.strip() 
     if td.find('strong'): 
      bold_time = cur_time 
     cur_time += datetime.timedelta(hours=1) 

print data.get(bold_time) # bold 
print data.get(bold_time - datetime.timedelta(hours=1)) # before bold 
print data.get(bold_time - datetime.timedelta(hours=2)) # before before bold 

이는 굵은 글씨로 표시하고 두 값이 (있는 경우) 앞에있는 3-hr PSI 값을 인쇄합니다.

희망이 있습니다.

+0

고마워요. 당신은 좋은 하루 보내길 바랍니다! =) –

+0

웹 사이트 업데이트가 있습니다. 코드를 어떻게 바꿀 수 있습니까? 으로 변경하려고하면 find_all (name = "div") [3] .find_all ('table') [0] 그것은 IndexError : list 인덱스가 범위를 벗어났습니다. http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours –

+0

'table = web_soup.find (name find_all (name = "div") [4] .find_all ('table') [0]'이 (가) 작동해야합니다. 희망이 도움이됩니다. – alecxe

0

이 코드 (#changed 텍스트 라인 참조)

from pprint import pprint 
import urllib2 
from bs4 import BeautifulSoup as soup 


url = "http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours" 
web_soup = soup(urllib2.urlopen(url)) 

table = web_soup.find(name="div", attrs={'class': 'c1'}).find_all(name="div")[2].find_all('table')[0] 

table_rows = [] 
for row in table.find_all('tr'): 
    table_rows.append([td.text.strip() for td in row.find_all('td')]) 

data = [] # changed 
for tr_index, tr in enumerate(table_rows): 
    if tr_index % 2 == 0: 
     for td_index, td in enumerate(tr): 
      data.append([td, table_rows[tr_index + 1][td_index]]) # changed 

pprint(data) 

당신에게

[[u'Time', u'3-hr PSI'], 
[u'12AM', u'57'], 
[u'1AM', u'-'], 
[u'2AM', u'-'], 
[u'3AM', u'-'], 
[u'4AM', u'-'], 
[u'5AM', u'-'], 
[u'6AM', u'-'], 
[u'7AM', u'-'], 
[u'8AM', u'-'], 
[u'9AM', u'-'], 
[u'10AM', u'-'], 
[u'11AM', u'-'], 
[u'Time', u'3-hr PSI'], 
[u'12PM', u'-'], 
[u'1PM', u'-'], 
[u'2PM', u'-'], 
[u'3PM', u'-'], 
[u'4PM', u'-'], 
[u'5PM', u'-'], 
[u'6PM', u'-'], 
[u'7PM', u'-'], 
[u'8PM', u'-'], 
[u'9PM', u'-'], 
[u'10PM', u'-'], 
[u'11PM', u'-']] 

print data[4:7]을주고 당신에게

를 제공
[[u'3AM', u'-'], [u'4AM', u'-'], [u'5AM', u'-']] 
관련 문제