【Excel VBA×Selenium】href・src・data属性の値を取得する方法|Attributeの使い方
みなさんこんにちは。
Excel VBAとSeleniumで、リンクや画像のURLが必要になることもあります。
今回は、Textでは取れないhref・src・data-*属性を、Attributeで取得する方法をご紹介します。
TextとAttributeの違い
Textは表示文字、Attribute("href")はHTMLの属性値を取得します。SeleniumBasicではGetAttributeではなくAttributeを使用する点がポイントよ。
今回使用するサンプルHTML
次をattribute-test.htmlとして保存し、Excelブックと同じ場所に置いてください。
<!DOCTYPE html>
<html lang="ja"><meta charset="UTF-8">
<h1>属性値取得テスト</h1>
<a id="productLink" href="https://www.selenium.dev/" data-product-id="A001">商品ページ</a>
<img id="productImage" src="https://www.selenium.dev/images/selenium_logo_square_green.png" width="80" alt="Seleniumロゴ">
</html>

Attributeで属性値を取得するVBAコード
「Selenium Type Library」を参照設定してください。
Option Explicit
Sub GetAttributeSample()
Dim driver As New Selenium.ChromeDriver
Dim linkEl As Selenium.WebElement
Dim imgEl As Selenium.WebElement
Dim v As Variant
Dim htmlPath As String
'テスト用HTMLの保存場所を確認
htmlPath = ThisWorkbook.Path & "\attribute-test.html"
If ThisWorkbook.Path = "" Or Dir(htmlPath) = "" Then
MsgBox "ブックとHTMLを同じ場所に保存してください。"
Exit Sub
End If
driver.Start "chrome"
driver.Get "file:///" & Replace(htmlPath, "\", "/")
'見つからない場合はNothingとして判定
Set linkEl = driver.FindElementById("productLink", 3000, False)
Set imgEl = driver.FindElementById("productImage", 3000, False)
If linkEl Is Nothing Or imgEl Is Nothing Then
MsgBox "対象要素がありません。"
Else
'表示文字とHTML属性を取得
Debug.Print "Text:" & linkEl.Text
Debug.Print "href:" & linkEl.Attribute("href")
Debug.Print "src:" & imgEl.Attribute("src")
Debug.Print "data-product-id:" & linkEl.Attribute("data-product-id")
'属性がなければNullや空値が返る場合がある
v = linkEl.Attribute("data-missing")
If IsNull(v) Or IsEmpty(v) Then
Debug.Print "data-missing:値なし"
ElseIf CStr(v) = "" Then
Debug.Print "data-missing:値なし"
End If
End If
driver.Quit
End Sub

href・src・data属性の取得結果
Text:商品ページ
href:https://www.selenium.dev/
src:https://www.selenium.dev/images/selenium_logo_square_green.png
data-product-id:A001
data-missing:値なし
要素・属性が存在しない場合の注意点
要素がないときはFindElementByIdの第3引数をFalseにしてNothingを判定します。属性がない場合もNullや空文字を確認してください。
要素の探し方は
も参考にしてください。
最後に
いかがでしたでしょうか。今回は、Attributeで属性値を取得する方法をご紹介しました。少しでも参考になれば幸いです。
開発依頼について
ココナラでWebスクレイピング開発サービスを出品しております。
自分で開発をしようと思ったけど、VBAでのネット記事が少なく困っている方も多いかと思います。
そんな方はいつでもお気軽にご相談ください。
また、本ブログからご依頼いただいた方については割引特典がございますので、
ご不明点と合わせてメッセージをいただけると幸いです。
業務の流れをまるごと自動化します Excel・Web・Teams・SaaSで業務全体を自動化Webスクレイピング以外にもWebアプリの開発サービスも出品しております。
こちらについても、本ブログからご依頼いただいた方については割引特典がございますので、
お気軽にご相談ください。
スモールスケールのWebアプリ開発します 先ずはスモールスケールのWebアプリから始めませんか?
