我完全难过了。我正在使用VBA的Internet Explorer对象解析谷歌图像搜索的HTML。当我使用Chrome的内置工具检查元素时,我得到的HTML就像这样:
<a href="/imgres?imgurl=...&imgrefurl=...&docid=...&tbnid=...&vet=...&w=1366&h=768&bih=638&biw=1366&q=cats&ved=...;iact=mrc&uact=8" jsaction="fire.ivg_o;mouseover:str.hmov;mouseout:str.hmou" class="rg_l" rel="noopener" style="background: rgb(200, 190, 194); width: 270px; height: 168px; left: 0px;"><img class="rg_ic rg_i" data-sz="f" name="z7O-qKoPKHzyaM:" alt="Image result for cat's" jsaction="load:str.tbn" onload="google.aft&&google.aft(this)" src="data:image/jpeg;base64,/9j/4AAQ..." style="width: 300px; height: 168px; margin-left: -15px; margin-right: -15px; margin-top: 0px;"><div class="_aOd rg_ilm"><div class="rg_ilmbg"><span class="rg_ilmn"> 1366 × 768 - wallpapercave.com </span></div></div></a>
或作为图片(抱歉,不知道如何格式化)
样式集中有一个“背景”值,我想得到这个。但是我似乎无法在任何地方找到它。当我使用Chrome的检查工具浏览属性时,没有“样式”选项可供查看。 InnerHTML
不包含某些样式元素,但不包含“背景”。
并通过VBA
HTMLelement.getAttribute("Background") = ""
HTMLelement.Style.Background = ""
HTMLelement.Style.BackgroundColor = ""
发生了什么,为什么我在使用网页检查器时会看到背景属性,但却无法通过上述方式访问它?
答案 0 :(得分:0)
为此,可以使用目标getAttribute("style")
元素的anchor
方法。然后style
的类型为IHTMLStyle
,其中包含 background 颜色的字符串属性。 HTH
Option Explicit
' Add reference to Microsoft Internet Controls (SHDocVw)
' Add reference to Microsoft HTML Object Library
Const url As String = "your-url-here"
Sub GetInlineStyle()
Dim ie As SHDocVw.InternetExplorer
Dim doc As MSHTML.HTMLDocument
Debug.Assert Trim(url) <> ""
Set ie = New SHDocVw.InternetExplorer
ie.Visible = True
ie.navigate url
While ie.Busy Or ie.readyState <> READYSTATE_COMPLETE
DoEvents
Wend
Set doc = ie.document
' Get target anchor element which contains the background color
Dim anchor As HTMLAnchorElement
Set anchor = doc.querySelector("a[class=rg_l]")
' Use getAttribute("style") to get style of anchor
Dim style As IHTMLStyle
Set style = anchor.getAttribute("style")
' IHTMLStyle has string property backgroundColor
Dim bgrColor As String
bgrColor = style.backgroundColor
Debug.Print bgrColor
ie.Quit
End Sub
输出
rgb(200, 190, 194)
使用HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- saved from url=(0016)http://localhost -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Stackoverflow Greedo</title>
</head>
<body>
<div class="content">
<a href="https://stackoverflow.com" class="rg_l" rel="noopener"
style="background: rgb(200, 190, 194); width: 270px; height: 168px; left: 0px">
Stackoverflow Greedo
</a>
</div>
</body>
</html>