宝くじと過ごす日々

Excel,VBA,Radio,モキュメンタリー好き事務の活動記録です。

【Selenium×VBA】複数のワードの検索ヒット数をサイト毎に自動取得【自動化】

今回作ったものは

複数の検索ワード(上限10万個)を検索サイト(GoogleとYahoo! JAPAN)でそれぞれ検索してヒット数を自動で取得してワークシートに出力していく資料」です。

イメージはこちら↓

f:id:osushidaisukikun:20210816162026j:image

ヒット数を調べたいワードをB3セルから下へ入力していってください。

上限は10万ですが、さすがにやりすぎるといろいろ危険な気がするので100ぐらいで留めてください。

役に立つかどうかは分かりませんが、とりあえず置いておきます。

わからない点があったらTwitterまで連絡ください。

豚にポン酢@たかはし (@butapon_9453) | Twitter

今回の資料で役に立ちそうなポイントはこちら。

  • VBAでの関数(WorksheetFunction.CountA)
  • VBAでセルの中身のみ削除する方法
  • seleniumでIDによる要素の取得方法
  • seleniumでclassによる要素の取得方法
  • seleniumでxPathによる要素の取得方法

↓ここから下を標準モジュールに貼り付け↓

Sub word_hit_search()

'起動シートの初期処理----------------------------------------------

Set Thisbk = ThisWorkbook

Dim ms As Worksheet

Set ms = Thisbk.Sheets("メイン")

Dim Google As String

Dim Yahoo As String

Dim Bing As String

Dim goo As String

Google = "https://www.google.com/"

Yahoo = "https://www.yahoo.co.jp/"

 

ms.Range("C3:D100000").ClearContents '100以上の場合はクリアする範囲を広げてください。

Dim word As String

Dim i As Long

Dim cnt As Long

cnt = Application.WorksheetFunction.CountA(ms.Range("B3:B100000"))

'起動シートの初期処理----------------------------------------------

'selenium----------------------------------------------

Dim Driver As New Selenium.ChromeDriver

Driver.AddArgument "--incognito" 'シークレットモード

Driver.AddArgument "disable-gpu"

Driver.AddArgument "start-maximized"

Driver.AddArgument "headless" 'バックグラウンド処理

Call Driver.Start("chrome")

'selenium----------------------------------------------

'繰り返し----------------------------------------------

For i = 1 To cnt

word = ms.Cells(2 + i, 2)

'Google
Driver.get Google

'Driver.Wait 500

Driver.FindElementByXPath("/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input").SendKeys word

Driver.FindElementsByClass("gNO89b")(2).Submit

ms.Cells(2 + i, 3) = Driver.FindElementById("result-stats").Text

'Yahoo!
Driver.get Yahoo

'Driver.Wait 500

Driver.FindElementByClass("_1wsoZ5fswvzAoNYvIJgrU4").SendKeys word

Driver.FindElementByClass("PHOgFibMkQJ6zcDBLbga8").Click

ms.Cells(2 + i, 4) = Driver.FindElementByClass("Hits__item").Text

Next i

'繰り返し----------------------------------------------

Driver.Close

End Sub

↑ここから下を標準モジュールに貼り付け↑

 

f:id:osushidaisukikun:20210816161553j:image