参考サイト
https://excel-ubara.com/excelvba4/EXCEL_VBA_401.html
https://powervbadesktop.com/web0/
英検準1級の勉強を始めたので英英辞書から単語の定義を取得するVBAを組んでみた。
WebDriverにwebページの指定をする
Const dictionaryURL As String = "https://www.oxfordlearnersdictionaries.com/definition/english/"
Set Driver = New Selenium.WebDriver
targetUrl = dictionaryURL & word
Driver.AddArgument "headless"
Driver.Start "Chrome"
Driver.Get targetUrl
英英辞書はoxfordを使う
oxfordの辞書は
https://www.oxfordlearnersdictionaries.com/definition/english/
の後に単語を付ければいいので
dictionaryURL & word
で指定している
![dictionary](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F99234%2Fa803266b-34de-3ee0-b2b3-8bc0abd66121.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=ded83aebcb7cc8fa6f77a4cfd0bbde6d)
Driver.AddArgument "headless"
上記指定でChromeをバックグラウンドで実行できる
ディベロッパーツールでタグを特定する
単語の定義をドラック > 右クリック > 検証
![dictionary](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F99234%2Fac204bc4-3a32-8945-ceef-e25a19a3fa8c.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=a256a8d565b0160e0eb1d14855b4231f)
タグを確認する
class="def"であることが分かる
![dictionary](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F99234%2F9d80889e-8fc5-585a-9e6a-83214ac6696b.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=2eb5fc71ffc9a23be34dc613da7a70b6)
タグを指定して要素を特定する
Dim defElements As WebElements
Dim defs As String
Dim defCnt As Integer
Dim ans As Integer
Set defElements = Driver.FindElementsByClass("def")
'すべての説明を結合する
For defCnt = 1 To defElements.Count
defs = defs & defCnt & vbCrLf & defElements.Item(defCnt).Text & vbCrLf
Next
ans = InputBox("入力する定義を選択してください" & vbCrLf & _
"99=全ての定義を入力する" & vbCrLf & vbCrLf & _
defs)
Select Case ans
Case 99
Cells(ActiveCell.Row, columnEngDesc).Value = defs
Case Else
Cells(ActiveCell.Row, columnEngDesc).Value = defElements.Item(ans).Text
End Select
Set defElements = Driver.FindElementsByClass("def")
上記でdefクラスの要素に絞り込む
For defCnt = 1 To defElements.Count
defs = defs & defCnt & vbCrLf & defElements.Item(defCnt).Text & vbCrLf
Next
すべての定義を結合する
ans = InputBox("入力する定義を選択してください" & vbCrLf & _
"99=全ての定義を入力する" & vbCrLf & vbCrLf & _
defs)
Select Case ans
Case 99
ActiveCell.offset(0,1).Value = defs
Case Else
ActiveCell.offset(0,1).Value = defElements.Item(ans).Text
End Select
![dictionary](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F99234%2F33644ef8-1900-d4d8-2fff-4b53b294643e.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=e326762c6e47350aa76cce120b3ee424)
結合した定義をinputboxで表示しどの定義を取得するか番号を入力してもらう
99を入力した場合はすべての定義を入力する