netkeiba.com様からpythonとBeautifulsoupで競馬情報をスクレイピングする中で、特定の馬のコードにおいて、途中でエラーが出てしまい、苦慮しております!
# -*- coding:utf-8 -*- import urllib2 import codecs import time from bs4 import BeautifulSoup f = codecs.open('horse1.csv', 'w',encoding='CP932', errors='replace') url='http://db.netkeiba.com/horse/2007100135/' soup = BeautifulSoup(urllib2.urlopen(url).read(),"lxml") tr_arr = soup.select("table.db_h_race_results > tbody > tr") for tr in tr_arr: time.sleep(1) tds=tr.findAll("td") nobori=tds[22].text #上り print nobori.strip() cols = [nobori] f.write(",".join(cols) + "\n")
上記のソースコードを動かしてみますと、以下のような結果になります。
Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\satoru>cd horse C:\Users\satoru\horse>cd horse C:\Users\satoru\horse\horse>horse-scan_s.py 41.5 392(-4) Traceback (most recent call last): File "C:\Users\satoru\horse\horse\horse-scan_s.py", line 19, in <module> nobori=tds[22].text #荳翫j IndexError: list index out of range C:\Users\satoru\horse\horse>horse-scan_s.py C:\Users\satoru\horse\horse>horse-scan_s.py C:\Users\satoru\horse\horse>horse-scan_s.py 41.5 Traceback (most recent call last): File "C:\Users\satoru\horse\horse\horse-scan_s.py", line 19, in <module> nobori=tds[22].text #荳翫j IndexError: list index out of range C:\Users\satoru\horse\horse>horse-scan_s.py C:\Users\satoru\horse\horse>horse-scan_s.py 41.5 40.9 42.9 43.1 42.5 37.5 41.0 40.7 42.6 Traceback (most recent call last): File "C:\Users\satoru\horse\horse\horse-scan_s.py", line 19, in <module> nobori=tds[22].text #荳翫j IndexError: list index out of range C:\Users\satoru\horse\horse>
ご覧のように、毎回、アクセスするたびに、違う答えが返ってきます
http://db.netkeiba.com/horse/2007100135/
スイセンキョウという、お馬さんです。
かたや、他のお馬で同じ事を行ってみます
# -*- coding:utf-8 -*- import urllib2 import codecs import time from bs4 import BeautifulSoup f = codecs.open('horse1.csv', 'w',encoding='CP932', errors='replace') url='http://db.netkeiba.com/horse/2010100483/' soup = BeautifulSoup(urllib2.urlopen(url).read(),"lxml") tr_arr = soup.select("table.db_h_race_results > tbody > tr") for tr in tr_arr: time.sleep(1) tds=tr.findAll("td") nobori=tds[22].text #上り print nobori.strip() cols = [nobori] f.write(",".join(cols) + "\n") f.close()
http://db.netkeiba.com/horse/2010100483/
トーキングドラムというお馬さんです
C:\Users\satoru\horse\horse>horse-scan_s.py 34.5 34.7 35.3 35.2 35.4 36.1 34.3 34.5 33.9 34.2 35.3 33.7 33.8 33.2 34.7 34.1 34.1 35.8 34.1 35.6 37.3 38.7 37.9 C:\Users\satoru\horse\horse>
このように、順調にデータをスクレイピングすることが出来ます。
この、スイセンキョウという馬の何が問題なのか、御教示いただければ幸いに思います。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。