VBA 代码 - Selenium - 使用 ng-binding 抓取网页

时间:2021-04-27 18:11:23

标签: html vba selenium head

这里是新手!

我组装了一个代码,试图获取出现在 html 页面“head”元素中的文本:1.3253/1.3325 XRP/USD - GateHub Markets

代码不会产生任何错误,它只是输出:total count = 1,但不是我试图提取的文本。

关于如何调整它的想法,好吗??

这是我要抓取的页面的 HTML:

<html lang="en" ng-app="landing" class="ng-scope">
<head><style type="text/css">@charset "UTF-8";[ng\:cloak],[ng-cloak],[data- 
ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate) 
{display:none !important;}ng\:form{display:block;}.ng-animate- 
shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>

<!--
   _____       _       _    _       _
  / ____|     | |     | |  | |     | |
 | |  __  __ _| |_ ___| |__| |_   _| |__
 | | |_ |/ _` | __/ _ \  __  | | | | '_ \
 | |__| | (_| | ||  __/ |  | | |_| | |_) |
  \_____|\__,_|\__\___|_|  |_|\__,_|_.__/

 GateHub is a platform for the Internet of Value.

 -->
  <meta charset="utf-8">
   <base href="/">
   <title ng-bind="pageTitle" class="ng-binding">1.3253/1.3325 XRP/USD - 
 GateHub Markets</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">

这是试图提取部分内文本的代码

Option Explicit
Private cd As Selenium.ChromeDriver

Sub New1()

Dim FindBy As New Selenium.By
Dim Results As Selenium.WebElements
Dim Result As Selenium.WebElement

Set cd = New Selenium.ChromeDriver
cd.Start
cd.get "https://gatehub.net/markets/XRP/USD+rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq"

If Not cd.IsElementPresent(FindBy.Tag("title"), 3000) Then
cd.Quit
MsgBox ("Not found!")
Exit Sub
End If

Set Results = cd.FindElementsByTag("title")
Debug.Print "Total found =" & Results.Count

Dim n As Long
For n = 1 To Results.Count
Debug.Print Results(n).Text
Next
cd.Quit
End Sub

1 个答案:

答案 0 :(得分:0)

您定位到了错误的属性。此元素的 css 样式设置为无显示。

enter image description here

例如,您需要 innerHTMLtextContent

d.FindElementByCss('title').Attribute('innerHTML')
d.FindElementByCss('title').Attribute('textContent')

Note.textContent:

与innerText的区别

<块引用>

不要被 Node.textContent 和 HTMLElement.innerText。虽然名字看起来很像 重要区别:

  1. textContent 获取所有元素的内容,包括 和 元素。相比之下,innerText 只显示“人类可读” 元素。
  2. textContent 返回节点中的每个元素。相比之下, innerText 知道样式并且不会返回“隐藏”的文本 元素。
  3. 此外,由于innerText考虑了CSS样式,阅读 innerText 的值触发回流以确保最新的计算 样式。 (回流在计算上可能很昂贵,因此应该 尽可能避免。)