質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

954閲覧

netkeiba.com様から希望する情報がスクレイピング出来ず、苦慮しております

akakage13

総合スコア89

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2018/02/20 14:28

編集2018/02/21 02:57

スクレイピング初心者でございます。

netkeiba.com様から希望する情報がスクレイピング出来ず、苦慮しております。

# -*- coding:utf-8 -*- import urllib2 import codecs import time from bs4 import BeautifulSoup f1 = codecs.open('tokyo_race_1.csv', 'w', 'utf-8') f1.write('other_race_name'+u"\n") url_1='http://race.netkeiba.com/?pid=race_old&id=p201805010301' soup_1 = BeautifulSoup(urllib2.urlopen(url_1).read(),"lxml") other_race_name_tag_1 = soup_1.find('div',{'class':'race_otherdata'}).find('p') other_race_name_1 = "".join([x for x in other_race_name_tag_1.text if not x == u'\xa0' and not x == u'\n']) cols = [other_race_name_1.strip()] f1.write(",".join(cols) + "\n") print other_race_name_1 f1.close()

上記のスクリプトでは、一行目の 1回 東京3日目 3歳 は 取れるのですが、

目的とする、二行めの、 16頭 が 取ることが出来ず、苦慮しております。

試したこと

二行目を取る方法として、当該ソースコードを 見てみましたところ以下のような構造でした。

1R </dt> <dd> <h1>3歳未勝利</h1> <p><span>ダ1300m&nbsp;/&nbsp;天気:晴&nbsp;/&nbsp;馬場:不良&nbsp;/&nbsp;発走:11:00</span></p> </dd> </dl> <div class="race_otherdata"> <p>1回東京3日目&nbsp;3歳&nbsp;</p> <p>牝[指定]&nbsp;16頭</p> <p>本賞金:500、200、130、75、50万円</p> </div> <ul class="btn_link_list fc">

上記の 1回 東京3日目 3歳はとれるので、<p> </p>で囲まれている全てを取ろうと考えて、上記のスクリプトのfindの箇所を

other_race_name_tag_1 = soup_1.find('div',{'class':'race_otherdata'}).findall('p') other_race_name_1 = "".join([x for x in other_race_name_tag_1.text if not x == u'\xa0' and not x == u'\n'])

findall に改変して試しましたが、

other_race_name_tag_1 = soup_1.find('div',{'class':'race_otherdata'}).findall('p') TypeError: 'NoneType' object is not callable

と、エラーが出てきました。Typeerrorについて調べましたが、うまく動きませんでした。

二行めの16 を取る方法を 御教示 よろしくお願いいたします。

umyu様、丁寧な御教示ありがとうございます。

うまく動きました。ただ、

ご助言にもございましたが、小生、python3.5に移行中でございます。

そのため、今回のスクリプトをpython3.5に改変しましたところ、

以下のようなスクリプトになりました。

# -*- coding:utf-8 -*- import urllib.request import codecs import time from bs4 import BeautifulSoup f1 = codecs.open('tokyo1.csv', 'w', 'utf-8') f1.write('other_race_name'+u"\n") url_1='http://race.netkeiba.com/?pid=race_old&id=c201805010801' soup_1 = BeautifulSoup(urllib.request.urlopen(url_1), "html.parser") #race1 tr_arr_1 = soup_1.select("table.race_table_old > tr ") for tr_1 in tr_arr_1: #time.sleep(0.25) tds_1 = tr_1.findAll("td") if len( tds_1 ) > 1: other_race_name_tag_1 = soup_1.find('div',{'class':'race_otherdata'}).find('p') other_race_name_1 = "".join([x for x in other_race_name_tag_1.text if not x == u'\xa0' and not x == u'\n']) cols = [other_race_name_1.strip()] f1.write(",".join(cols) + "\n") print (other_race_name_1.strip()) f1.close()

上記のスクリプトは一行目まではうまく動きます。

しかしながら、今回の目的の二行目までを取得しようとして、

御教示いただいたように、下記の通りに改変しましたが、うまく動きませんでした。

# -*- coding:utf-8 -*- import urllib.request import codecs import time from bs4 import BeautifulSoup f1 = codecs.open('tokyo1.csv', 'w', 'utf-8') f1.write('other_race_name'+u"\n") url_1='http://race.netkeiba.com/?pid=race_old&id=c201805010801' soup_1 = BeautifulSoup(urllib.request.urlopen(url_1), "html.parser") #race1 tr_arr_1 = soup_1.select("table.race_table_old > tr ") for tr_1 in tr_arr_1: #time.sleep(0.25) tds_1 = tr_1.findAll("td") if len( tds_1 ) > 1: other_race_name_tag_1 = soup_1.find('div',{'class':'race_otherdata'}).find_all('p') other_race_name_1 = "".join([x for x in other_race_name_tag_1.text if not x == u'\xa0' and not x == u'\n']) cols = [other_race_name_1.strip()] f1.write(",".join(cols) + "\n") print (other_race_name_1.strip()) f1.close()

下記のエラーが出てきました。

Traceback (most recent call last): File "C:\Users\satoru\satoru_system\race_data_scan\tokyo\1_tokyo_race_data_scan.py", line 23, in <module> other_race_name_1 = "".join([x for x in other_race_name_tag_1.text if not x == u'\xa0' and not x == u'\n']) File "C:\Users\satoru\AppData\Local\Programs\Python\Python36\lib\site-packages\bs4\element.py", line 1807, in __getattr__ "ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?``` python3.5におけるfindの使い方について、再度ご助言頂けますと助かります。 よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

umyu

2018/02/20 16:11

うまく出来ませんでした。ではなく、「質問するときのヒント」をhttps://teratail.com/help/question-tipsのページを参考にどのようなキーワードで調べたとか、そういう内容を質問文に追記してくださいな。
guest

回答1

0

ベストアンサー

TypeError: 'NoneType' object is not callable

ぐーぐる翻訳
TypeError: 'NoneType'オブジェクトは呼び出し可能ではありません

このメッセージが発生する条件は以下の2パターンが多いです。
パターン1,値がNoneの変数に対して関数を呼び出そうとした。
質問文の場合はsoup_1.find('div',{'class':'race_otherdata'})の戻り値がNoneで、それに対して.findall()関数をよびだそうとした
パターン2,呼び出し関数のスペルミス。今回の場合はこちらです。

○/×関数名
×.findall
.find_all

2行目の値も取り出したいとのことなので以下のソースコードでご要望の処理になりますか?

Python

1# -*- coding: utf8 -*- 2import urllib2 3import codecs 4import time 5from bs4 import BeautifulSoup 6 7 8def get_content(url): 9 from contextlib import closing 10 with closing(urllib2.urlopen(url)) as response: 11 return BeautifulSoup(response.read()) 12 13 14def get_data(soup): 15 i = 0 16 for parent in soup.find('div', {'class': 'race_otherdata'}): 17 unicode_strings = unicode(parent.string).rstrip() 18 if len(unicode_strings) == 0: 19 continue 20 if i == 2: 21 # 本賞金以降はSkip 22 continue 23 yield unicode_strings 24 i += 1 25 26 27def main(): 28 with codecs.open('tokyo_race_1.csv', 'w', 'utf-8') as f1: 29 f1.write('other_race_name' + u"\n") 30 url = 'http://race.netkeiba.com/?pid=race_old&id=p201805010301' 31 soup = get_content(url) 32 for row in get_data(soup): 33 f1.write(row + "\n") 34 35 36if __name__ == '__main__': 37 main()

■参考情報
Beautiful Soup 4.2.0 Doc. 日本語訳 (2013-11-19最終更新)

■余談
このコードを記述する時に一番時間がかかった点はpython 2.7環境でのunicode文字列の変換部分でした。
制約事項などがない場合はpython 3環境に移行することをおすすめいたします。


質問文のソースコードは回答した内容が一切反映されていないソースコードなのですが・・・その点。

まず、スクリプトの各変数の影響範囲を少なくすることを考えてくださいな。
質問文の改訂されたソースコードだと、どの箇所が問題になっているか、一瞬では原因究明が行えないと思います。

それは、以下の3つの処理を一つのスクリプト内で行っているからです。

1,WEBサイトからスクレイピング
2,スクレイピングしたデータをタグを指定して該当部分を抽出
3,抽出した内容をcsvファイルに書き出し。

こういう時は回答文のソースコードのように3つに関数を分割化を行います。
1,get_content
2,get_data
3,main

こうすることで、関数内と渡すパラメータだけ意識すればよくなり影響範囲が少なくなります。

python 3バージョンのソースコードです。

Python

1# -*- coding: utf8 -*- 2import urllib.request 3from bs4 import BeautifulSoup 4 5 6def get_content(url:str): 7 """ 8 @params url スクレイピング対象のURL 9 """ 10 with urllib.request.urlopen(url) as response: 11 return BeautifulSoup(response.read(), "html.parser") 12 13 14def get_data(soup) -> str: 15 i = 0 16 for parent in soup.find('div', {'class': 'race_otherdata'}): 17 data = parent.string.rstrip() 18 if len(data) == 0: 19 continue 20 if i == 2: 21 # 本賞金以降はSkip 22 continue 23 yield data 24 i += 1 25 26 27def main() -> None: 28 url = 'http://race.netkeiba.com/?pid=race_old&id=p201805010301' 29 soup = get_content(url) 30 # python 3なのでcodec.openは不要 31 with open('tokyo_race_1.csv', 'w', encoding='utf-8') as f: 32 f.write('other_race_name' + u"\n") 33 for row in get_data(soup): 34 print(row) 35 f.write(row + "\n") 36 37 38if __name__ == '__main__': 39 main()

投稿2018/02/21 00:10

編集2018/02/21 12:23
umyu

総合スコア5846

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

akakage13

2018/02/21 22:26

umyu様、python2.7-3.5両方における御教示、本当にありがとうございました。 今後ともよろしくお願いいたします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問