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

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

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

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Beautiful Soup

Beautiful Soupは、Pythonのライブラリの一つ。スクレイピングに特化しています。HTMLデータの構文の解析を行うために、HTMLタグ/CSSのセレクタで抽出する部分を指定することが可能です。

Python 3.x

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

Q&A

解決済

1回答

383閲覧

PythonでBeautifulSOUP, seliniumを使って画像取得しようとした際にエラーが発生

ethanoch

総合スコア3

Jupyter

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Beautiful Soup

Beautiful Soupは、Pythonのライブラリの一つ。スクレイピングに特化しています。HTMLデータの構文の解析を行うために、HTMLタグ/CSSのセレクタで抽出する部分を指定することが可能です。

Python 3.x

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

0グッド

0クリップ

投稿2023/05/30 15:03

編集2023/06/01 12:55

実現したいこと

BeautifulSOUP, selinium を使って該当画像のURLへ遷移したい。

前提

Pythonでwebサイトの画像をブラウザ表示する。コードを書きたいです。
Jupyter notebooksを使っています。

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

--------------------------------------------------------------------------- JavascriptException Traceback (most recent call last) Input In [14], in <cell line: 1>() ----> 1 driver.execute_script(s) 2 element=driver.find_element_by_id("refererurllink") 3 element.click() File ~\anaconda3\envs\PYTHON\lib\site-packages\selenium\webdriver\remote\webdriver.py:634, in WebDriver.execute_script(self, script, *args) 631 else: 632 command = Command.EXECUTE_SCRIPT --> 634 return self.execute(command, { 635 'script': script, 636 'args': converted_args})['value'] File ~\anaconda3\envs\PYTHON\lib\site-packages\selenium\webdriver\remote\webdriver.py:321, in WebDriver.execute(self, driver_command, params) 319 response = self.command_executor.execute(driver_command, params) 320 if response: --> 321 self.error_handler.check_response(response) 322 response['value'] = self._unwrap_value( 323 response.get('value', None)) 324 return response File ~\anaconda3\envs\PYTHON\lib\site-packages\selenium\webdriver\remote\errorhandler.py:242, in ErrorHandler.check_response(self, response) 240 alert_text = value['alert'].get('text') 241 raise exception_class(message, screen, stacktrace, alert_text) --> 242 raise exception_class(message, screen, stacktrace) JavascriptException: Message: javascript error: Cannot set properties of null (setting 'innerHTML') (Session info: headless chrome=113.0.5672.127)
--------------------------------------------------------------------------- ElementNotInteractableException Traceback (most recent call last) Input In [11], in <cell line: 12>() 10 element=driver.find_element_by_id("refererurllink") 11 driver.implicitly_wait(20) ---> 12 element.click() 13 result = requests.get(atags.source["srcset"],headers={"User-Agent": UA,"referer": url}) File ~\anaconda3\envs\PYTHON\lib\site-packages\selenium\webdriver\remote\webelement.py:80, in WebElement.click(self) 78 def click(self): 79 """Clicks the element.""" ---> 80 self._execute(Command.CLICK_ELEMENT) File ~\anaconda3\envs\PYTHON\lib\site-packages\selenium\webdriver\remote\webelement.py:633, in WebElement._execute(self, command, params) 631 params = {} 632 params['id'] = self._id --> 633 return self._parent.execute(command, params) File ~\anaconda3\envs\PYTHON\lib\site-packages\selenium\webdriver\remote\webdriver.py:321, in WebDriver.execute(self, driver_command, params) 319 response = self.command_executor.execute(driver_command, params) 320 if response: --> 321 self.error_handler.check_response(response) 322 response['value'] = self._unwrap_value( 323 response.get('value', None)) 324 return response File ~\anaconda3\envs\PYTHON\lib\site-packages\selenium\webdriver\remote\errorhandler.py:242, in ErrorHandler.check_response(self, response) 240 alert_text = value['alert'].get('text') 241 raise exception_class(message, screen, stacktrace, alert_text) --> 242 raise exception_class(message, screen, stacktrace) ElementNotInteractableException: Message: element not interactable (Session info: chrome=114.0.5735.90)

該当のソースコード

Python

1import requests 2from bs4 import BeautifulSoup 3from time import sleep 4from selenium import webdriver 5 6""" 7UI仕様準備 8""" 9options = webdriver.ChromeOptions() 10options.add_argument('--headless') 11options.add_argument('--no-sandbox') 12options.add_argument('--lang=ja') 13options.add_argument('--disable-dev-shm-usage') 14options.add_argument('--incognito') 15UA= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36" 16options.add_argument('--user-agent=' + UA) 17driver = webdriver.Chrome('chromedriver.exe',options=options) 18driver.implicitly_wait(10) 19 20 21url = "https://store.shopping.yahoo.co.jp/kodawarishokuhonpo/0025-15.html?sc_i=shp_pc_top_reco1" 22driver.get(url) 23html = driver.page_source.encode("utf-8") 24soup=BeautifulSoup(html, "html.parser") 25driver.set_window_size('1200', '1000') 26driver.implicitly_wait(10) 27atags=soup.find_all("img") 28image=atags[0].get("src") 29 30 31s = "var refererselector=document.getElementById('tab');refererselector.innerHTML=\"<a id='refererurllink' href='"+image+"' >吹っ飛べ!</a>\"" 32print(s) 33 34driver.execute_script(s) 35element=driver.find_element_by_id("refererurllink") 36element.click() 37result = requests.get(image,headers={"User-Agent": UA,"referer": url})

試したこと

print(s)の内容
var refererselector=document.getElementById('tab');refererselector.innerHTML="<a id='refererurllink' href='https://s.yimg.jp/c/logo/f/2.0/shopping_r_34_2x.png' >吹っ飛べ!</a>"
をコピペして該当サイトのコンソールに張り付けたところ正常に動作しました。

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

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

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

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

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

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

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

guest

回答1

0

ベストアンサー

refererselectornullということなので、document.getElementById('tab')が見つからなかったということです。

コピペして該当サイトのコンソールに張り付けたところ正常に動作しました。

と言うことであれば、
・見ているページが違う
・タイミングの問題
のどちらかです。

ヘッドレスを止めて画面を表示し、driver.execute_script(s)の直前にinput("継続?")とか入れて、そこでプログラムを一旦止めて、そのブラウザ画面でdocument.getElementById('tab')を実行してみましょう。

投稿2023/05/31 09:50

otn

総合スコア84555

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

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

ethanoch

2023/06/01 12:57

ご回答ありがとうございます。 ・見ているページが違う ・タイミングの問題 両方が原因だったようです、不安定ですが上のエラーは解決しました。 しかし、「発生している問題・エラーメッセージ」の下のほうのエラーが出てしまいました。sleep等使ってみたのですが解決はしませんでした。このエラーはどのようにすればよいでしょうか?
otn

2023/06/01 14:34

element not interactable なので、クリックできない状態だと言うことです。 ・表示されていない ・disableになっている ・上に何か別の要素がかぶっている など。最初の2つは is_displayed() と is_enabled() でわかりますが、 該当したらどうしたら良いかは、はHTMLとCSSを読み解く力が必要です。
ethanoch

2023/06/02 11:52

ありがとうございます。おそらく画面サイズが小さく、該当箇所がクリックできないレイアウトになったのが原因と思われます。 画面を大きくしたらエラーは消えました。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問