python2.7とBeautifulsoupで競馬情報をスクレイピングする中で、競走結果が無い馬を飛ばして情報を読み込むことが出来ず、苦慮しております!
# -*- coding:utf-8 -*- import urllib2 import codecs import time from bs4 import BeautifulSoup f = codecs.open('h2007_5.csv', 'w', 'utf-8') horse_name = "" start_url = 'http://db.netkeiba.com/horse/200710{0}/' for i in xrange(1,10000): url = start_url.format(i) soup = BeautifulSoup(urllib2.urlopen(url).read(), "lxml") time.sleep(3) horse_name_tag = soup.find('div', {'class': 'horse_title'}) tr_arr1 = soup.select("table.blood_table > tr > td") t_list = tr_arr1 if horse_name_tag != None: if horse_name_tag.find('h1') != None: horse_name = horse_name_tag.find('h1').text horse_name = "".join( [x for x in horse_name_tag.text if not x == u'\xa0' and not x == u'\n']) tr_arr = soup.select("table.db_h_race_results > tbody > tr") for tr in tr_arr: tds=tr.findAll("td") race_date=tds[0].a.text #日付 print horse_name.strip(),race_date.strip() cols = [ horse_name,race_date] f.write(",".join(cols) + "\n") else: continue f.close()
上記のソースコードは、うまく動くことは動くのですが、
tr_arr = soup.select("table.db_h_race_results > tbody > tr") for tr in tr_arr: tds=tr.findAll("td") race_date=tds[0].a.text #日付 print horse_name.strip(),race_date.strip() cols = [ horse_name,race_date] f.write(",".join(cols) + "\n") else: continue f.close()
後半部分の、上記の部分以降、つまりrace_results が無い馬が現れると、プログラムが止まり困っております。
上記部分の情報がない場合でも、馬名を取得して、連続して、次の馬名を読み込んでほしいのです。
先輩方の御教示、よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー