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

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

新規登録して質問してみよう
ただいま回答率
85.48%
スクレイピング

スクレイピングとは、公開されているWebサイトからページ内の情報を抽出する技術です。

Python 3.x

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

Python

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

Q&A

解決済

5回答

8200閲覧

【python】スクレイピング中ブラウザのアラートダイアログが出た場合、OKを押して処理を続けたい【Webスクレイピング】

pon_nyamo

総合スコア30

スクレイピング

スクレイピングとは、公開されているWebサイトからページ内の情報を抽出する技術です。

Python 3.x

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

Python

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

0グッド

0クリップ

投稿2020/09/20 02:01

編集2020/09/24 06:25

プログラム初心者です。

やりたいこと

スクレイピング中ブラウザのアラートダイアログが出た場合、OKを押して処理を続けたい

困っていること

BeautifulSoupというpythonのパッケージに入っている部分でエラーとなっています。
このような事象が初めてでどのように修正したらよいかがわからずにいます。

・パッケージの中身を修正するしか手段がないのか?
・自身のプログラム上の修正方法があるのか?

何か修正方法や助言をいただきたいです。

該当のソースコード

python

1 2~~~~略~~~~ 3 4# CSVファイルを開く。ファイルがなければ新規作成する。 5f = open("date.csv", "w", encoding='utf-8') 6writecsv = csv.writer(f, lineterminator='\n') 7 8with open('URL.csv', encoding="utf_8") as fp: 9 lists = list(csv.reader(fp)) 10 11# 一行ずつ取得する 12for date in lists: 13 14 csvlist = [] 15 16 url = date[0] 17 sales_status = date[1] 18 19 driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe") 20 driver.get(url); 21 time.sleep(10) 22 23 soup = BeautifulSoup(driver.page_source, "html.parser") 24 25 errthtml = soup.find("div", attrs={"class", "errorDetail"}) 26 27~~~~略~~~~ 28

↑ここの「BeautifulSoup」の中身でエラーになってます。

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

Traceback (most recent call last): File "C:hogehoge.py", line 51, in <module> soup = BeautifulSoup(driver.page_source, "html.parser") File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 679, in page_source return self.execute(Command.GET_PAGE_SOURCE)['value'] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 241, in check_response raise exception_class(message, screen, stacktrace, alert_text) selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。 Message: unexpected alert open: {Alert text : 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。} (Session info: chrome=85.0.4183.102)

試したこと・調べたこと

上記で「UnexpectedAlertPresentException」が発生したため、
soup = BeautifulSoup(driver.page_source, "html.parser") の前後にtryを付けてみました。

また、ブラウザ上でアラートダイアログが出た場合は、
ダイアログの操作する処理をすればよいと検索で見つけたので試してみました。

ですが、そもそもBeautifulSoupの中でエラーになっているので意味がなかったです・・・。

python

1while True: 2 try: 3 soup = BeautifulSoup(driver.page_source, "html.parser") 4 except UnexpectedAlertPresentException: 5 driver.switch_to.alert.accept() 6 print("Alert accepted") 7 else: 8 break

バージョン

Python 3.7.3

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

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

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

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

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

otn

2020/09/20 02:14 編集

BeautifulSoupじゃなくてSeleniumでのエラーですね。
pon_nyamo

2020/09/20 02:17

「発生している問題・エラーメッセージ」と「該当のソースコード」の内容が合っていない、ということでしょうか?
otn

2020/09/20 02:19

↑すいません。見間違えたので、コメントを修正しています。
pon_nyamo

2020/09/20 03:12

ありがとうございます。 Seleniumのエラーなんですね、そのキーワードでは検索していなかったので検索してみます(*_ _)!
pon_nyamo

2020/09/20 05:20

解決策が出てこなかったため、このまま質問を続けます。
guest

回答5

0

ベストアンサー

手動で Chromeを 起動し URLにアクセスして
Alertが表示されるようであれば OKをクリックして
ブラウザを閉じる

その後
import os
を追記して
前回同様に 以下のコードに置き換えて実行してみて下さい

Python

1# CSVファイルを開く。ファイルがなければ新規作成する。 2f = open("date.csv", "w", encoding='utf-8') 3writecsv = csv.writer(f, lineterminator='\n') 4 5with open('URL.csv', encoding="utf_8") as fp: 6 lists = list(csv.reader(fp)) 7 8userdata_dir = 'C:/Users/' + os.getlogin()+ '/AppData/Local/Google/Chrome/User Data' 9 10options = webdriver.ChromeOptions() 11options.add_argument('--user-data-dir=' + userdata_dir) 12 13driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe",options=options) 14# 一行ずつ取得する 15for date in lists: 16 17 csvlist = [] 18 19 url = date[0] 20 sales_status = date[1] 21 22 23 driver.get(url) 24 time.sleep(10) 25 26 html = '' 27 try: 28 html = driver.page_source 29 print('Normal processing') 30 except UnexpectedAlertPresentException: 31 print('UnexpectedAlertPresentException Occured') 32 try: 33 time.sleep(3) 34 alert = driver.switch_to.alert 35 time.sleep(3) 36 print('Switched to alert') 37 alert.accept() 38 time.sleep(3) 39 print("Alert accepted") 40 41 html = driver.page_source 42 print('Error processing') 43 44 except Exception as e1: 45 print(str(e1) + ' Occured') 46 html = driver.page_source 47 48 except Exception as e2: 49 print(e2) 50 sys.exit(1) 51 52 soup = BeautifulSoup(html, "html.parser") 53 print('Passed') 54 55 errthtml = soup.find("div", attrs={"class", "errorDetail"})

投稿2020/09/27 03:03

編集2020/09/27 08:52
Reach

総合スコア733

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

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

pon_nyamo

2020/09/27 09:02

ご回答ありがとうございます! 上記の通り行ってみましたが、実行したところprintにたどり着く前にエラーとなりました。 headless chromeで行おうとすると、サイトから?アクセス拒否されてしまうようです。。。 [3808:7868:0927/174651.918:ERROR:cache_util_win.cc(21)] Unable to move the cache: アクセスが拒否されました。 (0x5) [3808:7868:0927/174651.919:ERROR:cache_util.cc(139)] Unable to move cache folder C:\Users\hogehoge\AppData\Local\Google\Chrome\User Data\ShaderCache\GPUCache to C:\Users\hogehoge\AppData\Local\Google\Chrome\User Data\ShaderCache\old_GPUCache_000 [3808:7868:0927/174651.920:ERROR:disk_cache.cc(184)] Unable to create cache [3808:7868:0927/174651.920:ERROR:shader_disk_cache.cc(606)] Shader Cache Creation failed: -2 既存のブラウザ セッションで開いています。 Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 31, in <module> driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe",options=options) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 81, in __init__ desired_capabilities=desired_capabilities) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir
pon_nyamo

2020/09/27 09:03

ちなみにheadless chrome抜きで、上記の「html = ''」以降のコードを書き換えて実行してみたところ、 「UnexpectedAlertPresentException Occured」はprintで表示されましたが、それ以降は前回と変わらずでした。 ※期待する確認方法でない場合は申し訳ございません・・・。 DevTools listening on ws://127.0.0.1:61469/devtools/browser/7b54cd82-5ac0-4081-8b25-d998af9d31a6 UnexpectedAlertPresentException Occured Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 48, in <module> html = driver.page_source File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 679, in page_source return self.execute(Command.GET_PAGE_SOURCE)['value'] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 241, in check_response raise exception_class(message, screen, stacktrace, alert_text) selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。 Message: unexpected alert open: {Alert text : 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。} (Session info: chrome=85.0.4183.121) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 54, in <module> alert = driver.switch_to.alert File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 55, in alert alert.text File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\common\alert.py", line 67, in text return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoAlertPresentException: Message: no such alert (Session info: chrome=85.0.4183.121)
Reach

2020/09/27 09:47

コマンドプロンプトから taskkill /F /IM chromedriver.exe と taskkill /F /IM chrome.exe を 実行後 先ほどの Python Scriptを 実行してみて下さい
Reach

2020/09/27 09:56

全コードを見ていないので 解りませんが for 文の中で driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe") を実行すると Chromeが 複数起動しませんか?
Reach

2020/09/27 10:07

非Headlessでのテストで userdata_dir = 'C:/Users/' + os.getlogin()+ '/AppData/Local/Google/Chrome/User Data' options = webdriver.ChromeOptions() options.add_argument('--user-data-dir=' + userdata_dir) driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe",options=options) を 書き換えなかった理由を 教えていただけないでしょうか?
pon_nyamo

2020/09/27 12:55 編集

ご回答ありがとうございます! 以下の回答時(1回目)は上記のheadless chromeの記述し実行したのですが、 「アクセスが拒否されました。」と表示され、headless chromeはサイトが拒否してできないのかな?と勘違いしてしまいました。。。 >2020/09/27 18:02 >ご回答ありがとうございます! >上記の通り行ってみましたが、実行したところprintにたどり着く前にエラーとなりました。 >headless chromeで行おうとすると、サイトから?アクセス拒否されてしまうようです。。。 その後(その勘違いをしたまま)、以下の回答時(2回目)でheadlessの記述を抜いてテストした次第です。 >2020/09/27 18:03 >ちなみにheadless chrome抜きで、上記の「html = ''」以降のコードを書き換えて実行してみたところ、 >「UnexpectedAlertPresentException Occured」はprintで表示されましたが、それ以降は前回と変わらずでした。 >※期待する確認方法でない場合は申し訳ございません・・・。
pon_nyamo

2020/09/27 12:57 編集

>全コードを見ていないので 解りませんが >for 文の中で >driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe") >を実行すると Chromeが 複数起動しませんか? 画面上では複数起動していませんが、タスクマネージャーは見てなかったのでもしかしたら複数起動してたかもしれません。。。 確かにforの中になくても良い記述なので外に出しておきます! ご指摘ありがとうございます。 【追記】 ・・・と思いforの外にやってみたのですが、今まで正常に動いていたものが途中で動かなくなってしまいました。 for1回目:正常終了 for2回目:対象のコンピューターによって拒否されたため、接続できませんでした。のエラーになる そのため、以下の記述forの中に入れた状態で行います。 driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe")
pon_nyamo

2020/09/27 12:59

なので、headless chromeはできないと勘違いしていたので、もう一度実行してみます。 ただし上記に記載したとおり、forの外にwebdriver.Chromeの記述を書くとなぜかエラーとなってしまうので、以下の記述は中に入れた状態でやってみます。 driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe",options=options)
pon_nyamo

2020/09/27 13:22 編集

実行しました!少し進展しました。 printは「UnexpectedAlertPresentException Occured」「print(e1 + ' Occured')」が出ています。 ---------------------------------------------------------------------- 【記述したコード(抜粋)】 ~~~(略)~~~ # CSVファイルを開く。ファイルがなければ新規作成する。 f = open("date.csv", "w", encoding='utf-8') writecsv = csv.writer(f, lineterminator='\n') with open('URL.csv', encoding="utf_8") as fp: lists = list(csv.reader(fp)) userdata_dir = 'C:/Users/' + os.getlogin()+ '/AppData/Local/Google/Chrome/User Data' options = webdriver.ChromeOptions() options.add_argument('--user-data-dir=' + userdata_dir) # 一行ずつ取得する for date in lists: csvlist = [] url = date[0] sales_status = date[1] driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe",options=options) #driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe") driver.get(url); time.sleep(10) html = '' try: html = driver.page_source print('Normal processing') except UnexpectedAlertPresentException: print('UnexpectedAlertPresentException Occured') try: time.sleep(3) alert = driver.switch_to.alert time.sleep(3) print('Switched to alert') alert.accept() time.sleep(3) print("Alert accepted") html = driver.page_source print('Error processing') except Exception as e1: print(e1 + ' Occured') html = driver.page_source except Exception as e2: print(e2) sys.exit(1) soup = BeautifulSoup(html, "html.parser") print('Passed') errthtml = soup.find("div", attrs={"class", "errorDetail"}) ~~~(略)~~~ ---------------------------------------------------------------------- ---------------------------------------------------------------------- 【エラー時のログ】 DevTools listening on ws://127.0.0.1:52163/devtools/browser/9f2c3902-9272-4d50-b8a5-483f2a110a7e UnexpectedAlertPresentException Occured Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 48, in <module> html = driver.page_source File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 679, in page_source return self.execute(Command.GET_PAGE_SOURCE)['value'] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 241, in check_response raise exception_class(message, screen, stacktrace, alert_text) selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。 Message: unexpected alert open: {Alert text : 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。} (Session info: chrome=85.0.4183.121) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 54, in <module> alert = driver.switch_to.alert File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 55, in alert alert.text File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\common\alert.py", line 67, in text return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoAlertPresentException: Message: no such alert (Session info: chrome=85.0.4183.121) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 65, in <module> print(e1 + ' Occured') TypeError: unsupported operand type(s) for +: 'NoAlertPresentException' and 'str' ----------------------------------------------------------------------
Reach

2020/09/27 13:31

> 実行しました!少し進展しました。 printは「UnexpectedAlertPresentException Occured」「print(e1 + ' Occured')」が出ています。 print(str(e1) + ' Occured') です (コードを修正したので)
pon_nyamo

2020/09/27 13:38

す、すみません・・・上記はprintの記述エラーですね。失礼しました。 もう一度実行してみます。
Reach

2020/09/27 13:48

下に alert = driver.switch_to.alert を 使わないコード記載してあるので そちらも 試していただけたら 幸いです
pon_nyamo

2020/09/27 15:00

わー!凄いです!落ちることなく、正常にすべて処理が終わりました! 最後にCSV出力をおこなっているのですが、そちらの出力内容も問題ありません。 本当にありがとうございます( ;∀;)!!! ちなみにアラートダイアログが出た時は以下の通りprintされました。 --------------- DevTools listening on ws://127.0.0.1:57531/devtools/browser/65db8449-e832-45f3-ab11-6ab5dc8fcc03 UnexpectedAlertPresentException Occured Message: no such alert (Session info: chrome=85.0.4183.121) Occured Passed --------------- ①「UnexpectedAlertPresentException Occured」:UnexpectedAlertPresentExceptionに入り ②「Message: no such alert」:alert = driver.switch_to.alertでのメッセージ→Exception ③「Occured」:上記でExceptionが発生し「except Exception as e1:」に入り、html = driver.page_sourceでソースを取得し ④「soup = BeautifulSoup(html, "html.parser")」で③のデータを抽出 ⑤「Passed」:で正常に通りました。
Reach

2020/09/27 15:08

どうやら alert = driver.switch_to.alert で 2回目の エラーが発生するので 下のコードでは 別の手法で試しています
pon_nyamo

2020/09/27 15:23

tryの中にtryって入れられるんですね・・・プログラムが独学初心者でまだそのレベルです・・・。 お時間をさいていただきありがとうございます。 本当に助かりました。こちらの内容で実行していこうと思います。
guest

0

from time import sleep # 追加

sleep (5) # 追加
alert = driver.switch_to_alert()
alert.accept()

投稿2020/09/22 20:25

Reach

総合スコア733

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

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

pon_nyamo

2020/09/22 22:50

ご回答いただきありがとうございます。 上記の通り sleep を入れてみましたが、先日と同じエラーが出てしまいました・・・・。 ※sleep (5)、sleep (10)と2つ試しましたが同様です。
guest

0

try: soup = BeautifulSoup(driver.page_source, "html.parser") except UnexpectedAlertPresentException: alert = driver.switch_to_alert() alert.accept() print("Alert accepted") else: break

投稿2020/09/22 09:51

Reach

総合スコア733

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

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

pon_nyamo

2020/09/22 10:52 編集

ご回答いただきありがとうございます。 上記で試してみましたが、試したこと・調べたことで行った時と同じエラーが出てしまいました。 そのようなアラートはないと以下のエラーメッセージででていますが、アラートダイアログは画面上出ているんです・・・。 Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 59, in <module> alert = driver.switch_to_alert() File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 803, in switch_to_alert return self._switch_to.alert File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 55, in alert alert.text File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\common\alert.py", line 67, in text return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoAlertPresentException: Message: no such alert (Session info: chrome=85.0.4183.102)
Reach

2020/09/23 08:17

> 試したこと・調べたことで行った時と同じエラーが出てしまいました。 UnexpectedAlertPresentException: と NoAlertPresentException: では 別のエラーです
pon_nyamo

2020/09/24 06:18

紛らわしくて申し訳ございません。 「該当のソースコード」※tryなど無しで実行した結果のエラーが 「発生している問題・エラーメッセージ」のUnexpectedAlertPresentExceptionです。 上記の「該当のソースコード」でExceptionが発生したため 「試したこと・調べたこと」として、新たにtryのコードを書き、実行しましたが 試したこと・調べたことで行った時と同じエラー(NoAlertPresentException)が発生した、ということです。 該当のソースコードの前後の記載を追記しておきます。
guest

0

こちらの検証も お願い致します

Python

1html = '' 2try: 3 html = driver.page_source 4 print('Normal processing') 5except UnexpectedAlertPresentException: 6 print('UnexpectedAlertPresentException Occured') 7 try: 8 time.sleep(3) 9 #alert = driver.switch_to.alert 10 time.sleep(3) 11 driver.find_element_by_tag_name('html').send_keys(Keys.ENTER) 12 print('Switched to alert') 13 #alert.accept() 14 time.sleep(3) 15 print("Alert accepted") 16 17 html = driver.page_source 18 print('Error processing') 19 except Exception as e1: 20 print(str(e1) + ' Occured') 21 html = driver.page_source 22 23except Exception as e2: 24 print(e2) 25 sys.exit(1) 26

こちらでの実行結果 (https://www.seleniumeasy.com/test/javascript-alert-box-demo.html)
UnexpectedAlertPresentException Occured
Switched to alert
Alert accepted
Error processing
Passed

投稿2020/09/27 10:52

編集2020/09/27 13:57
Reach

総合スコア733

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

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

pon_nyamo

2020/09/27 15:09

こちらの記述でも正常に処理が行えました! ありがとうございます。 アラートダイアログが出た時は以下の通りprintされました。 --------------- DevTools listening on ws://127.0.0.1:61359/devtools/browser/b06c7594-cd70-48f3-a3d1-94912ea6f03b UnexpectedAlertPresentException Occured Switched to alert Alert accepted Error processing Passed --------------- ①「UnexpectedAlertPresentException Occured」:UnexpectedAlertPresentExceptionに入り ②driver.find_element_by_tag_name('html').send_keys(Keys.ENTER) で要素を取得?? ※すみませんここは何をしているのか、いまいちよくわかりませんでした・・・。 https://www.seleniumqref.com/api/python/element_get/Python_find_element_by_tag_name.html https://www.seleniumqref.com/api/python/element_set/Python_special_send_keys.html ③「Switched to alert」「Alert accepted」:②の後のprint ④html = driver.page_sourceでソースを取得 ⑤「Error processing」:④の後のprint ⑥「soup = BeautifulSoup(html, "html.parser")」で④のデータを抽出 ⑦「Passed」:で正常に通りました。
Reach

2020/09/27 15:14

> driver.find_element_by_tag_name('html').send_keys(Keys.ENTER) Chromeに Enterを 送信 (alertを クリックする操作)です
Reach

2020/09/27 15:17

'html' の代わりに 'body' でも大丈夫みたいです
pon_nyamo

2020/09/27 15:23

そんな方法はあるとは知りませんでした・・・! ありがとうございます勉強になりました。
guest

0

以下コードに置き換えて
print文が どう表示されるか 教えて下さい

importされてるとは 思いますが
from selenium.common.exceptions import UnexpectedAlertPresentException
を 未だのようなら 追記して下さい

Python

1# 一行ずつ取得する 2for date in lists: 3 4 csvlist = [] 5 6 url = date[0] 7 sales_status = date[1] 8 9 driver = webdriver.Chrome(executable_path="C:\chromedriver_win32\chromedriver.exe") 10 driver.get(url) 11 time.sleep(10) 12 13 14 try: 15 soup = BeautifulSoup(driver.page_source, "html.parser") 16 print('Normal processing') 17 except UnexpectedAlertPresentException: 18 alert = driver.switch_to.alert 19 time.sleep(3) 20 print('Switched to alert') 21 alert.accept() 22 time.sleep(3) 23 print("Alert accepted") 24 25 soup = BeautifulSoup(driver.page_source, "html.parser") 26 print('Error processing') 27 except Exception as e: 28 print(e) 29 30 31 print('Passed') 32 33 34 errthtml = soup.find("div", attrs={"class", "errorDetail"})

投稿2020/09/26 05:25

Reach

総合スコア733

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

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

pon_nyamo

2020/09/27 09:01 編集

ご回答ありがとうございます!とても嬉しいです・・・! ※以下はすでに記述しています from selenium.common.exceptions import UnexpectedAlertPresentException 上記ご回答いただいたコードの通り記述したところ以下の結果となりました。 アラートダイアログがでる時は「alert = driver.switch_to.alert」の中でエラーとなっているため、print文が表示されませんでした。。 ★アラートダイアログが出た時(今回の件) ```python DevTools listening on ws://127.0.0.1:58606/devtools/browser/f326869d-ba58-4dd5-b5b3-dcf101521c10 Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 56, in <module> soup = BeautifulSoup(driver.page_source, "html.parser") File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 679, in page_source return self.execute(Command.GET_PAGE_SOURCE)['value'] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 241, in check_response raise exception_class(message, screen, stacktrace, alert_text) selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。 Message: unexpected alert open: {Alert text : 您的浏览器限制了第三方Cookie,这将影响您正常登录,您可以更改浏览器的隐私设置,解除限制后重试。} (Session info: chrome=85.0.4183.121) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\hogehoge\hogehoge.py", line 59, in <module> alert = driver.switch_to.alert File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 55, in alert alert.text File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\common\alert.py", line 67, in text return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"] File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\hogehoge\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoAlertPresentException: Message: no such alert (Session info: chrome=85.0.4183.121) ``` ★【補足】アラートダイアログが出ないとき(正常な時) ```python DevTools listening on ws://127.0.0.1:54585/devtools/browser/ddb717fe-eb3c-46e7-bab7-10999298f47b Normal processing Passed ```
Reach

2020/09/27 03:14

ちょっと 疑問なのですが、Alertが 出るときと 出ないときが あるのでしょうか? 【Alertが 出るとき】 soup = BeautifulSoup(driver.page_source, "html.parser") 実行で UnexpectedAlertPresentException 発生 alert = driver.switch_to.alert に移り NoAlertPresentException が 発生という 流れなのでしょうか?
pon_nyamo

2020/09/27 05:37

そうなんです。アラートが出る時と出ない時があるんです。。 何かアラートがでる条件があるのかな?と、アラートが出たURLをリストアップしたり、何回目のURL実行で再現するのか・・・など調べてみたのですが、特に規則性はなく・・・・。 ※スクレイピング実行1回目でアラートダイアログが出る場合もあれば、10回目で出る時もあります アラートが出る時は以下の認識で合っています! >soup = BeautifulSoup(driver.page_source, "html.parser") >実行で UnexpectedAlertPresentException 発生 >alert = driver.switch_to.alert >に移り NoAlertPresentException が 発生という 流れなのでしょうか? アラートダイアログが表示されてる状態で、上記の流れで最終的にNoAlertPresentExceptionが発生し、落ちています。アラートはあるはずなのに「Message: no such alert」と表示され、お手上げ状態です・・・。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問