前提・実現したいこと
「株とPython-自作プログラムでお金儲けを目指す」という書籍でpythonの勉強をしています。
株の銘柄情報の取得とSQliteへの格納がしたいです。
下記リンクも参照しながら該当するソースコードを実行してみたのですが、
エラーメッセージが発生して先に進めないです。
https://bitop.hatenablog.com/entry/2019/04/09/060131
データベースもリンク通りDB Browser for SQliteを使っています。
Windows版(64bit)です。
発生している問題・エラーメッセージ
python
1--------------------------------------------------------------------------- 2OperationalError Traceback (most recent call last) 3<ipython-input-16-c378ba6b20b8> in <module> 4----> 1 insert_brands_to_db('kabud.db',range(1301,1320)) 5 6<ipython-input-13-a7e9fa617c9c> in insert_brands_to_db(db_file_name, code_range) 7 37 sql = 'INSERT INTO brands(code,name,short_name,market,unit,sector) ' \ 8 38 'VALUES(?,?,?,?,?,?)' 9---> 39 conn.executemany(sql, brands_generator(code_range)) 10 11OperationalError: no such table: brands
該当のソースコード
from pyquery import PyQuery import time import sqlite3 def get_brand(code): url = 'https://kabutan.jp/stock/?code={}'.format(code) q = PyQuery(url) if len(q.find('div.company_block')) == 0: return None try: name = q.find('div.company_block > h3').text() code_short_name = q.find('#stockinfo_i1 > div.si_i1_1 > h2').text() short_name = code_short_name[code_short_name.find(" ") + 1:] market = q.find('span.market').text() unit_str = q.find('#kobetsu_left > table:nth-child(4) > tbody > tr:nth-child(6) > td').text() unit = int(unit_str.split()[0].replace(',', '')) sector = q.find('#stockinfo_i2 > div > a').text() except (ValueError, IndexError): return None return code, name, short_name, market, unit, sector def brands_generator(code_range): for code in code_range: brand = get_brand(code) if brand: yield brand time.sleep(1) #サーバーに迷惑をかけないための配慮 def insert_brands_to_db(db_file_name, code_range): conn = sqlite3.connect(db_file_name) with conn: sql = 'INSERT INTO brands(code,name,short_name,market,unit,sector) ' \ 'VALUES(?,?,?,?,?,?)' conn.executemany(sql, brands_generator(code_range))
insert_brands_to_db('kabud.db',range(1301,1320)) #勉強段階なので狭い範囲で試しています。
試したこと
ファイル名はkabud.dbにしたのですが、ここの名前を参照リンク通りbrands.dbにファイル名およびコードを変えても同じように
OperationalError: no such table: brands
のエラーがでます。下記のbrandsをたとえばbrandにいじるとエラーは
no such talbe:brandsに変わりました。
def insert_brands_to_db(db_file_name, code_range): conn = sqlite3.connect(db_file_name) with conn: sql = 'INSERT INTO brands(code,name,short_name,market,unit,sector) ' \#←ここのbrandsをいじるとエラーも変わる。 'VALUES(?,?,?,?,?,?)' conn.executemany(sql, brands_generator(code_range))
参照リンクhttps://bitop.hatenablog.com/entry/2019/04/09/060131のようにTableやfieldも入力したのですが、
なぜエラー(認識していない?)が起きるのかがわからないです。kabud.dbというファイルは確かに存在します。
わかる方解決策を教えてください。
##追記
修正依頼にありました、テーブルの状態について追記します。画像の通りです。
https://bitop.hatenablog.com/entry/2019/04/09/060131
のリンクの通り進めています。
リンクの通りテーブル名をbrandsにするのも試してみたのですが、同様に
OperationalError: no such table: brands
になります。
##追記その2
saziさんのおっしゃる通りカレントディレクトリで解決しました。
なぜか参照リンクhttps://bitop.hatenablog.com/entry/2019/04/09/060131のような
表への反映はされないですが、エラーは出なくなりました。
回答1件
あなたの回答
tips
プレビュー