Published Date : 2020年11月8日20:49

Seleniumを使用して複数のタブを開く
Use Selenium to open multiple tabs


This blog has an English translation


YouTubeにアップした動画、「【日本語解説】Seleniumを使用して複数のタブを開く【Python, Firefox】」の補足説明の記事です。

Here's a little more about the 「【Python】Use Selenium to open multiple tabs【Firefox】」 video I uploaded to YouTube.

字幕を付けるなら、英語音声と日本語音声の二つに分けたほうが良いと思ったので、今回から同じ動画だが音声が日本語と英語に分かれたものをアップしました。

I thought it would be better to separate the video into English audio and Japanese audio instead of adding subtitles to the video, so I uploaded the same video with Japanese and English audio separately.

ページの頭に日本語解説動画、ページの最後に英語解説動画のリンクが貼られてます。

There is a Japanese explanation video at the top of the page, and an English explanation video link at the end of the page.


目次

Table of Contents




① 動画の説明
① Video Description



例えばfirefoxで沢山のタブを開いてWEBサイトを表示しているとします。

For example, suppose you open a lot of tabs in firefox and open a website.

それらをブラウザを閉じた後にまた表示したいのであれば、

If you want to see those pages again after you close your browser,

このようにブックマークで管理しているかと思います。

you're probably managing them with bookmarks like this.

ブックマークを使いたくない理由がある時は、

If there's a reason you don't want to use bookmarks,

firefoxのオプションから、カスタムURLの機能を使っても、

you can use firefox's custom URL feature

一度に複数のWEBサイトを記録しておくことができます。

to record multiple websites at once.

今回はこのfirefoxの機能と、PythonとSeleniumを使って、少し遊んでみましょう。

This time, Let's play with this firefox feature and Python and Selenium for a bit.

PythonとSeleniumとWebDriverの簡単なセットアップと使用方法は、以前の動画を参考にしてくだちぃ。

For a quick setup and use of Python, Selenium, and WebDriver, check out the video I uploaded earlier.

まずはfirefoxで適当に複数のタグでWEBサイトを表示させてみてください。

First of all, let firefox display a website using multiple tags.

その後、先ほど説明したオプションから、カスタムURLの機能を使って表示させていたURLをコピーします。

Then, select a custom URL from the options described earlier, and copy the URL that you are displaying.

適当な作業用フォルダを作成して、

Create an appropriate working folder.

その中にURL用のフォルダとURLを記録させたテキストファイルを作成します。

Create a folder for the URL in it. Then, Create a text file containing the URL.

このように、複数のURLが「バーティカルバー」で区切られています。

In this way, multiple URLs are separated by [vertical bar].

複数のURLを表示させるPythonのスクリプトファイルを作成します。

Create a Python script file that displays multiple URLs.

まずはテキストを読み込み、split関数を使い「バーティカルバー」で区切ってリストにします。

First load the text and use the split function to create a list separated by [vertical bar].

それをまたリストに格納していきます。

We will store it in the list again.

上手くいっているかテストしてみましょう。

Let's test it to see if it works.

seleniumを使った箇所はコメントアウトしてくだちぃ。

Please comment out where selenium is used.

テストが終わったら、コメントアウトを外して、

At the end of the test, uncomment the lines you just commented out

For文を使ってリストのURLを一つずつ取り出すようにします。

and use the For statement to retrieve the list URLs one at a time.

そしてdriverのexecute_scriptメソッドを使用して、

Then use the execute_script method in driver to

Javascriptで別タブを開いてURLにアクセスさせるようにします。

using Javascript open another tab and access the URL.

このwindow.openとアンダースコアblankとswitch_to.windowメソッドについて簡単に説明します。

I will briefly explain window.open, _blank and switch_to.window method.

WEBサイトを開いている時に、URLのリンクをクリックしてみましょう。

Let's click the URL link on the page where the website is open.

すると、今開いているページが更新されてリンク先のURLにアクセスされました。

Then, the page that is open now was updated and the URL of the link was accessed.

新しいタブを開いてそこに表示させたい場合は、コントロール+クリックを使います。

To open a new tab and display it, use Control + Click.

aタグの内容を変えても同じことができます。

The same can be done by changing the contents of the a tag.

インスペクターエレメントでHTMLの要素を変えてみましょう。

Let's use the Inspector element to change the HTML elements.

対象のaタグで右クリックしてAttributes、Add Attributeを選択します。

Right-click on the target a tag and select Attributes, Add Attribute.

[target = "_blank"]と入力してEnterを押します。

Type [target = "_blank"] and press Enter.

その状態で同じリンクをクリックしてみてください。

Then click the link you edited.

別の新しいタブを開いてリンク先にアクセスできました。

Now you can open another new tab and go to the link.

これと同じ事がexecute_scriptメソッドで行われています。

So, something similar is happening in the Javascript used in the execute_script method.

次にswitch_to.windowメソッドについてです。

Now let's look at the switch_to.window method.

これは名前が示す通り、今開いているウィンドウを切り替えます。

This toggles the currently open window, as the name implies.

その際に、現在操作できるウィンドウをリストで表示できるdriverのwindow_handlesを使用してあげます。

Use the driver's window_handles, which lists the currently available windows.

リストの要素のインデックス番号に[-1]を指定すると、リストの最後の要素を取り出してくれます。

Specifying [-1] as the index number of a list element will retrieve the last element in the list.

ご覧の通り、ウィンドウが切り替わっているのが分かります。

As you can see, the window is switching.

まあ、今回のようなただ単にWEBサイトを表示させるだけの場合、switch_to.windowメソッドは無くても大丈夫です。

Well, In this case, you just want to display websites, you don't need the switch_to.window method.

ですが、switch_to.windowメソッドを使わないと、ウィンドウハンドルは最初のページのままです。

However, if you do not use the switch_to.window method, the window handle remains on the first page.

その状態で開いたタブのページに対して、何か操作をしたい場合、ご覧の通り例外が発生します。

If you want to do something with a tab page that's open in that state, you'll see an exception.

これを避けるにはswitch_to.windowメソッドを使用して、ウィンドウハンドルを操作したいウィンドウに切り替える必要があります。

To avoid this, you should use the switch_to.window method to switch the window handle to the window you want to manipulate.

ではスクリプトを動かしてみましょう。

Now let's run the script.

その前にコマンドラインからブラウザを閉じるか、そのまま見続けるかを操作できるようにWhile文を使用したスクリプトを追加します。

Before that, add a script that uses the While statement so that you can either close the browser from the command line or keep looking.

続いてswitch_to.windowメソッドをコメントアウトしてもう一度スクリプトを動かしてみましょう。

Now let's comment out the switch_to.window method and run the script again.

一瞬で終わりました。

It ended in a moment.

このように表示させるだけならswitch_to.windowメソッドを使わないほうが速く表示できます。

If you only want to display like this, it is faster to not use the switch_to.window method.

クロームドライバーで開く.py
import glob
from selenium.webdriver import Chrome, ChromeOptions

driver_path = r'C:\Users\user\chromedriver.exe'

options = ChromeOptions()
options.add_argument('--incognito')

driver = Chrome(
    executable_path=driver_path, options=options)

一時的なブックマークのパス = r"C:\Users\user\一時的なブックマーク\*"

一時的なブックマークファイル = glob.glob(一時的なブックマークのパス)

一時的なブックマークURLのリスト = []

for URLリスト in 一時的なブックマークファイル:
    with open(URLリスト, 'r') as f:
        URLリスト = f.read()
        URLリスト = URLリスト.split('|')
        一時的なブックマークURLのリスト.append(URLリスト)

for URLのリスト in 一時的なブックマークURLのリスト:
    for URL in URLのリスト:
        driver.execute_script(f"window.open('{URL}', '_blank');")
        # driver.switch_to.window(driver.window_handles[-1])

ブラウザを維持する = True
while ブラウザを維持する:
    閉じる = input('ブラウザを閉じますか? y/n : ')
    if 閉じる == 'y' or 閉じる == 'Y':
        driver.quit()
        ブラウザを維持する = False
        break

これに終了です。

That's all.

いや、ブックマークでいいでしょ。

Hmm, this is "troublesome", it is "easier" to use the bookmark.

今あなたはそう思ってるのではないでしょうか。

That's what I expected, what you just thought.

ではアディオス。

Adios.



以上です。お疲れ様です。

That's all. Thank you for your hard work.