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

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

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

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

selenium

Selenium(セレニウム)は、ブラウザをプログラムで作動させるフレームワークです。この原理を使うことにより、ブラウザのユーザーテストなどを自動化にすることができます。

Q&A

解決済

1回答

9646閲覧

TypeError: object of type 'NoneType' has no len()の解決法について

makamaka

総合スコア21

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

selenium

Selenium(セレニウム)は、ブラウザをプログラムで作動させるフレームワークです。この原理を使うことにより、ブラウザのユーザーテストなどを自動化にすることができます。

0グッド

0クリップ

投稿2021/09/17 15:21

前提・実現したいこと

抽選サイトで抽選可能なものに申し込みを自動で行うシステムを作りたいと思っています。
抽選できるものには申し込みボタンがあり、自動で申し込みボタンを見つけ、クリックするシステムを組みたいと思っています。
1か所につき申し込みは一度まで、常に抽選があるのではなく、抽選がない場合には「不可」を出力され、システムを閉じるようにしたいです。
現在のシステムでは"不可"は出力され、サイトは閉じます。しかし、以下のようなエラーメッセージが出てしま

pythonのseleniumを使い、途中でつまずいてしまったため、解決方法をご教授いただきたいです。

発生している問題・エラーメッセージ

ERROR:root:Internal Python error in the inspect module. Below is the traceback from this internal error. Traceback (most recent call last): File "<ipython-input-104-ec29e3e3dcb7>", line 3, in <module> element = browser.find_element_by_xpath('//img[@alt=\"申込\"]') File "C:\anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element return self.execute(Command.FIND_ELEMENT, { File "C:\anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\anaconda\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//img[@alt="申込"]"} (Session info: chrome=93.0.4577.82) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 3437, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-104-ec29e3e3dcb7>", line 7, in <module> sys.exit() SystemExit During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\anaconda\lib\site-packages\IPython\core\ultratb.py", line 1101, in get_records return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) File "C:\anaconda\lib\site-packages\IPython\core\ultratb.py", line 248, in wrapped return f(*args, **kwargs) File "C:\anaconda\lib\site-packages\IPython\core\ultratb.py", line 281, in _fixed_getinnerframes records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) File "C:\anaconda\lib\inspect.py", line 1515, in getinnerframes frameinfo = (tb.tb_frame,) + getframeinfo(tb, context) AttributeError: 'tuple' object has no attribute 'tb_frame' --------------------------------------------------------------------------- NoSuchElementException Traceback (most recent call last) <ipython-input-104-ec29e3e3dcb7> in <module> 2 try: ----> 3 element = browser.find_element_by_xpath('//img[@alt=\"申込\"]') 4 except: C:\anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py in find_element_by_xpath(self, xpath) 393 """ --> 394 return self.find_element(by=By.XPATH, value=xpath) 395 C:\anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py in find_element(self, by, value) 975 value = '[name="%s"]' % value --> 976 return self.execute(Command.FIND_ELEMENT, { 977 'using': by, C:\anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute(self, driver_command, params) 320 if response: --> 321 self.error_handler.check_response(response) 322 response['value'] = self._unwrap_value( C:\anaconda\lib\site-packages\selenium\webdriver\remote\errorhandler.py in check_response(self, response) 241 raise exception_class(message, screen, stacktrace, alert_text) --> 242 raise exception_class(message, screen, stacktrace) 243 NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//img[@alt="申込"]"} (Session info: chrome=93.0.4577.82) During handling of the above exception, another exception occurred: SystemExit Traceback (most recent call last) [... skipping hidden 1 frame] <ipython-input-104-ec29e3e3dcb7> in <module> 6 browser.quit() ----> 7 sys.exit() SystemExit: During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) [... skipping hidden 1 frame] C:\anaconda\lib\site-packages\IPython\core\interactiveshell.py in showtraceback(self, exc_tuple, filename, tb_offset, exception_only, running_compiled_code) 2052 stb = ['An exception has occurred, use %tb to see ' 2053 'the full traceback.\n'] -> 2054 stb.extend(self.InteractiveTB.get_exception_only(etype, 2055 value)) 2056 else: C:\anaconda\lib\site-packages\IPython\core\ultratb.py in get_exception_only(self, etype, value) 752 value : exception value 753 """ --> 754 return ListTB.structured_traceback(self, etype, value) 755 756 def show_exception_only(self, etype, evalue): C:\anaconda\lib\site-packages\IPython\core\ultratb.py in structured_traceback(self, etype, evalue, etb, tb_offset, context) 627 chained_exceptions_tb_offset = 0 628 out_list = ( --> 629 self.structured_traceback( 630 etype, evalue, (etb, chained_exc_ids), 631 chained_exceptions_tb_offset, context) C:\anaconda\lib\site-packages\IPython\core\ultratb.py in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context) 1365 else: 1366 self.tb = tb -> 1367 return FormattedTB.structured_traceback( 1368 self, etype, value, tb, tb_offset, number_of_lines_of_context) 1369 C:\anaconda\lib\site-packages\IPython\core\ultratb.py in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context) 1265 if mode in self.verbose_modes: 1266 # Verbose modes need a full traceback -> 1267 return VerboseTB.structured_traceback( 1268 self, etype, value, tb, tb_offset, number_of_lines_of_context 1269 ) C:\anaconda\lib\site-packages\IPython\core\ultratb.py in structured_traceback(self, etype, evalue, etb, tb_offset, number_of_lines_of_context) 1122 """Return a nice text document describing the traceback.""" 1123 -> 1124 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, 1125 tb_offset) 1126 C:\anaconda\lib\site-packages\IPython\core\ultratb.py in format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset) 1080 1081 -> 1082 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records) 1083 1084 frames = self.format_records(records, last_unique, recursion_repeat) C:\anaconda\lib\site-packages\IPython\core\ultratb.py in find_recursion(etype, value, records) 380 # first frame (from in to out) that looks different. 381 if not is_recursion_error(etype, value, records): --> 382 return len(records), 0 383 384 # Select filename, lineno, func_name to track frames with TypeError: object of type 'NoneType' has no len()

該当のソースコード

python element = None try: element = browser.find_element_by_xpath('//img[@alt=\"申込\"]') except: print('不可') browser.quit() sys.exit()

試したこと

ここに問題に対して試したことを記載してください。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

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

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

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

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

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

holy_

2021/09/17 18:27

pythonを動かしている環境をおしえてください。
guest

回答1

0

ベストアンサー

スタックトレースから分かりますが、WindowsでJupyter Lab/Notebookを使っていますね。

試しに、質問文に示された内容と、それ以前のセルの内容をまとめた.pyファイルを作成し、Jupyterではなくコマンドラインで「python ファイル名.py」として実行してみてください。
すると、NoSuchElementException例外の発生時には、それをキャッチしたexcept節の処理(「不可」の表示など)の後、sys.exitSystemExit例外が発生し、特に何も表示せずにPythonが終了します。

いっぽう、Jupyterでは、カーネル(各セルの実行結果を保持しているPythonのプロセス)を気軽に止める訳にはいかないので、sys.exitを実行してSystemExit例外が発生しても、カーネルは終了しません。Jupyter側で捕捉したSystemExit例外のスタックトレースが表示されます。

Jupyterでは、セルに小分けしてコードを実行できるのですから、sys.exit()が不要になるようにコードを分割して書いてください。今回のコードからsys.exitをコメント化したものを使い、後続のセルではelementNoneかどうかをチェックするか、あなた自身が「不可」と表示されないときだけ後続のセルを実行すればいいでしょう。

投稿2021/09/17 23:14

Daregada

総合スコア11990

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

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

makamaka

2021/09/18 00:28

ご返答ありがとうございます。 ご指摘のとおり、コマンドプロンプトでpython ファイル名.pyを実行したところ、pythonと出力されただけでプログラムが起動しませんでした。もし、解決法等ご存知でしたらご教授ください。
Daregada

2021/09/18 00:39

環境変数PATHにAnacondaに付属するPythonを実行するためのパスが登録されていませんね。 ファイル名やオプションを指定したときに「Python」と表示されるのは、Microsoftが用意したStoreへの誘導用アプリで、本物のPythonではありません。 手軽に確認するには、スタートボタンからAnaconda Navigator(Anacondaのアプリ)のウィンドウを選んで、その中の「CMD.exe Prompt」の「Launch」ボタンを押すと開くコマンドプロンプトのウィンドウを使うことです。このコマンドプロンプトには、環境変数PATHにAnacondaに付属するPythonを実行するためのパスが自動登録されており、「python ファイル名.py」でファイルの内容を実行できます。 もちろん、環境変数PATHの設定を自分で書き替えれば、通常のコマンドプロンプトでも同じ結果が得られます。
makamaka

2021/09/19 00:13 編集

CMD.exe Promptで実行したところ、次のような出力になりました。たびたびで申し訳ありませんが、わかる範囲内でご教授ください。 python: can't open file 'IPO.py': [Errno 2] No such file or directory
Daregada

2021/09/19 00:21

「該当のソースコード」には書かれていませんが、IPO.pyを読むコードが書かれていて、そのファイルが見つからない、というエラーですね。
makamaka

2021/09/19 02:59

ご回答ありがとうございます。 パスが間違っていたようでしたので、正しいパスを指定し、python ファイル名.pyを実行したところ次のようなエラーが出ました。 File "select.py", line 7 pip install selenium ^ SyntaxError: invalid syntax 構文エラーのようですが、jupyterlabでは実行できているのでがなぜでしょうか。
Daregada

2021/09/19 04:46

ここは、あなたのコードを延々と手直しする場所ではなく、「ひとつの質問に対する回答を書く」ところです。最初に書いた質問が解決したら「解決済み」にしてください。 さて、最後にコメントすると、「pip install selenium」はPythonのコードではないからです。ちなみに、あなたのコメントは間違いで、JupterLabでもエラーになります。 JupyterLabでは、先頭に ! を付けて「!pip install selenium」とする必要がありますし、ファイル名.pyにはそれを書いてはいけません。 コマンドプロンプトを開いて、そこに「pip install selenium」を入力して実行します。
makamaka

2021/09/19 05:31

そうですねご指摘の通りです。 長々と教えていただき大変ためになりました。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.47%

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

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

質問する

関連した質問