1
7

More than 3 years have passed since last update.

Python Google翻訳からスクレイピング翻訳してExcelに保存

Last updated at Posted at 2021-02-20

0. はじめに

以前YouTubeで紹介した仕事や課題のさぼり方について解説する。エクセルに羅列された日本語を英語に翻訳するプログラムだ。WebDriverを用いてgoogle翻訳からスクレイピングで翻訳する。動作環境はChromで行う。

1. 必要ライブラリ

openpyxlseleniumtimeを用いる。openpyxlseleniumは予めpip等でインストールする必要がある。又、ブラウザ操作をするためChromDriverをダウンロードしpathを通しておく必要がある。

python -m pip install openpyxl
python -m pip install selenium
import openpyxl as excel
from selenium import webdriver
import time

2. Excelファイルの読み込みとDriverの設定

次にエクセルファイルを指定する。

book = excel.load_workbook("<Excelファイルのパス>", data_only=True)
sheet = book.worksheets[0]     #データのsheetを選択
driver = webdriver.Chrome()     #DriverをChromに設定
count = 1     #セルの行指定

3. データの読み込みとスクレイピングによる翻訳

先ほどを見込んだファイルからセルのデータを抽出し、Google翻訳で英訳する。返ってきた英語を受け取りExcelに書き込む。

while True:
    cell = sheet["A" + str(count)]     #cellの指定
    if cell.value:     #もしcellにデータがあれば
        url = "https://translate.google.co.jp/?hl=ja&sl=ja&tl=en&text={}&op=translate".format(cell.value)     #Google翻訳に日本語を入力済みのURLを作成
        driver.get(url)     #上記URLを開く
        time.sleep(1)     #サーバ負荷軽減
        ja = driver.find_element_by_css_selector("span[jsname='W297wb']")
        sheet["B" + str(count)] = ja.text
        count += 1
    else:
        break     #cellにデータがなければループを抜ける

4. Excelファイルを保存し実行

最後にExcelファイルを保存する。
実際にデバッグしてみるとChromが立ち上がり順次翻訳されるだろう。デバッグする際はExcelファイルは閉じてデバッグする。

book.save("<Excelファイルのパス>")

5. まとめ

課題をさぼれるが何の役にも立たない。課題はしっかりやって身に着けるべき。

1
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
7