单击以字符串开头的 HREF
Click on HREF that begins with a string
我在尝试点击 href 进入网页时遇到问题。 href 包含在 "a" 标签中,它的开头是这样的“http://trial.xxxyyy”。如何设置一个字符串,让我可以点击以前面提到的字符串开头的 href?我认为 queryselector 是关键,但我不熟悉它。
P.s 页面很空,所以没有太多内容 html。
尝试使用[attribute^=value]
CSS selector,它将选择href属性值以特殊值开头的每个元素。
示例代码如下:
Public Sub ClickTest()
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "<the website url>"
While .Busy Or .readyState <> 4: DoEvents: Wend
ie.Document.querySelector("a[href^='https://www.bing']").Click
End With
End Sub
这样的网站资源:
<a class="link" href="https://www.google.com/"> Google</a><br />
<a class="link" href="https://www.microsoft.com/en-us"> Microsoft</a><br />
<a class="link" href="https://www.bing.com/"> Bing</a><br />
<a class="link" href="https://www.bing.com/search?q=vba&qs=n&form=QBLH&sp=-1&pq=vba&sc=6-3&sk=&cvid=400A0A54265148289028B12BE5D9E3A4">Bing search</a>
[注意]如果有多个元素符合过滤条件,使用上面的代码,会获取第一个元素。
我在尝试点击 href 进入网页时遇到问题。 href 包含在 "a" 标签中,它的开头是这样的“http://trial.xxxyyy”。如何设置一个字符串,让我可以点击以前面提到的字符串开头的 href?我认为 queryselector 是关键,但我不熟悉它。
P.s 页面很空,所以没有太多内容 html。
尝试使用[attribute^=value]
CSS selector,它将选择href属性值以特殊值开头的每个元素。
示例代码如下:
Public Sub ClickTest()
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "<the website url>"
While .Busy Or .readyState <> 4: DoEvents: Wend
ie.Document.querySelector("a[href^='https://www.bing']").Click
End With
End Sub
这样的网站资源:
<a class="link" href="https://www.google.com/"> Google</a><br />
<a class="link" href="https://www.microsoft.com/en-us"> Microsoft</a><br />
<a class="link" href="https://www.bing.com/"> Bing</a><br />
<a class="link" href="https://www.bing.com/search?q=vba&qs=n&form=QBLH&sp=-1&pq=vba&sc=6-3&sk=&cvid=400A0A54265148289028B12BE5D9E3A4">Bing search</a>
[注意]如果有多个元素符合过滤条件,使用上面的代码,会获取第一个元素。