LoginSignup
5
6

More than 1 year has passed since last update.

【Python】英単語の音声ファイルをスクレイピングして集める

Posted at

タイトル通りです。
英単語の音声ファイルが欲しかったので、Weblioさんからスクレイピングして拝借したいと思います。

1単語の音声ファイルをスクレイピングする

import requests
from bs4 import BeautifulSoup
base_url = 'https://ejje.weblio.jp/content/'
# スクレイピングする英単語
word = 'experience'
url = base_url + word
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
try:
    # スクレイピング
    mp3_dl_url = soup.find('source')['src']
    response = requests.get(mp3_dl_url)
    mp3 = response.content
    # 音声ファイルを保存
    save_file = word + '.mp3'    
    with open(save_file,'wb') as f:
        f.write(mp3)
except:
    print('{}は見つかりません'.format(word))

複数の英単語の音声ファイルをスクレイピングする

1つだけの音声ファイルのためにスクレイピングしても面白くないので、もっと実用的に複数の英単語の音声ファイルを集めます。

英単語をスクレイピングして取得する

もともと、音声ファイルを集めたい英単語のリストとかを持っていれば必要ありませんが、今回は英単語のリストもスクレイピングして用意しようと思います。

こちらのサイトにTOEIC頻出英単語の一覧がありましたので、スクレイピングしてCSVファイルで保存しました。

import requests, csv
from bs4 import BeautifulSoup
url = 'https://englishlevelup.net/toeic-word-list/'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
w = soup.find_all('td')
word = []
for i in range(0,4000, 2): 
    tmp = []
    tmp.append(w[i].get_text())
    tmp.append(w[i+1].get_text())
    word.append(tmp)
# Chapterごとに単語を分ける
w1 = word[0:300]
w2 = word[300:600]
w3 = word[600:900]
w4 = word[900:1200]
w5 = word[1200:1500]
w6 = word[1500:1800]
w7 = word[1800:2000]
word_list = []
word_list += [w1,w2,w3,w4,w5,w6,w7]
# Chapterごとにファイルを分けて保存
for i,x in enumerate(word_list):
    filename = 'dict/chapter' + str(i+1) + '.csv'
    with open(filename,'w') as f:
        writer = csv.writer(f, lineterminator='\n')
        writer.writerows(x)

CSVファイルから複数の英単語の音声ファイルをスクレイピング

集めた英単語リストのCSVファイルを使って、Weblioさんから音声ファイルをスクレイピングします。

※Weblioに負荷をかけすぎないように注意してください。

import requests, csv, time
from bs4 import BeautifulSoup
base_url = 'https://ejje.weblio.jp/content/'
# Chapterの数だけループ
for i in range(1,8):
    filename = 'dict/chapter' + str(i) + '.csv'
    with open(filename) as f:
        reader = csv.reader(f)
        wordlist = [row for row in reader]
    # 各単語ごとにスクレイピングして音声ファイルを保存
    for w in wordlist:
        url = base_url + w[0]
        res = requests.get(url)
        soup = BeautifulSoup(res.text, 'html.parser')

        try:
            mp3_dl_url = soup.find('source')['src']
            print(w[0])

            response = requests.get(mp3_dl_url)
            mp3 = response.content
            save_file = './pronunciation/' + w[0] + '.mp3'

            with open(save_file,'wb') as f:
                f.write(mp3)
        except:
            print('{}は見つかりません'.format(w[0]))

        # weblioに負荷をかけすぎないよう間隔をあける!!
        time.sleep(5)
5
6
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
5
6