2017-08-10 16 views
0

私は野球チームの今日の試合で相手チームになりたいと思っています。私はBeautifulSoupを使用しています。imgタグのalt値を取得したい

私はこれをコード化しました。

このコードは、今日のゲームの情報をWebサイトから入手します。

from bs4 import BeautifulSoup 
import datetime 
import urllib.request 

req = urllib.request.Request("http://www.hanwhaeagles.co.kr/html/game/1st_schedule_list1.asp") 
data = urllib.request.urlopen(req).read() 

bs = BeautifulSoup(data, 'html.parser') 

l = bs.find_all('div') 
idx = 0 

for s in l: 
    try: 
     prop = s.get('class') 
     if prop != None and prop[0] == "box" and len(prop) == 2: 
      l = s 
      break 
    except UnicodeEncodeError: 
     print("Error") 
    finally: 
     idx += 1 

print(l) 

'変数l'は今日のゲームの情報です。

imgタグのalt値は相手チームのチーム名です。あなたはboxクラス内に存在するデータで、より興味を持っているので

私はそれを印刷したい...

答えて

1

に私を助けて。あなたが直接そのクラスさらに処理して抽出することができる:

from bs4 import BeautifulSoup 
import datetime 
import urllib.request 

req = urllib.request.Request("http://www.hanwhaeagles.co.kr/html/game/1st_schedule_list1.asp") 
data = urllib.request.urlopen(req).read() 
bs = BeautifulSoup(data, 'html.parser') 

for item in bs.select('.box'): 
    team_name = item.find('img')['alt'] 
    print(team_name) 

'NC' 
'NC' 
... 
+0

はそれを試みたが、.. –

+0

TEAM_NAME = chunck [0] .find( 'IMG')[ 'alt'] IndexError:リストインデックスが範囲外です –

+0

と私はチャックを印刷しました。値は[]です –

0
from bs4 import BeautifulSoup 
import urllib.request 

req = urllib.request.Request("http://www.hanwhaeagles.co.kr/html/game/1st_schedule_list1.asp") 
data = urllib.request.urlopen(req).read() 

bs = BeautifulSoup(data, 'html.parser') 

table = bs.find('table') 

for tr in table.find_all('tr'): 
    for td in tr.find_all('td'): 
     if td.find('img'): 
      if 'alt' in td.find('img').attrs: 
       print(td.find('img')['alt']) 

出力:

NC 
NC 
NC 
KIA 
KIA 
KIA 
두산 
두산 
삼성 
삼성 
넥센 
넥센 
SK 
SK 
NC 
NC 
롯데 
롯데 
KT 
KT 
KIA 
KIA 
SK 
SK 
LG 
LG 
KT 
+0

私はそれをしました。ありがとう! –

+0

は回答を受け入れますか?) –

関連する問題