Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 使用VBA从网站获取文本_Html_Vba_Internet Explorer_Dom_Web Scraping - Fatal编程技术网

Html 使用VBA从网站获取文本

Html 使用VBA从网站获取文本,html,vba,internet-explorer,dom,web-scraping,Html,Vba,Internet Explorer,Dom,Web Scraping,我需要创建一个VBA宏,它获取特定网站并搜索ID。找到ID后,我需要获取文本并将其复制到Excel中 以下是Webiste的源代码: <tr> <td style="width: 10%; color: blue" valign="top"><a name="111" id="111">111</td> <td><pre> Some text I Need in excel </pre></a&

我需要创建一个VBA宏,它获取特定网站并搜索ID。找到ID后,我需要获取文本并将其复制到Excel中

以下是Webiste的源代码:

<tr>
<td style="width: 10%; color: blue" valign="top"><a name="111" id="111">111</td>
<td><pre>  
    Some text I Need in excel
</pre></a><td>
</tr>
我还尝试了替代“.getAttribute”的其他方法,并尝试将元素用作字符串,但也不起作用


如果有人能帮我处理代码,那就太棒了:D

文本不在属性中,而是在pre元素中。因此
getAttribute
函数无法返回所需的文本

如果要获取第一个文本,请查看函数
querySelector
。此函数返回并接受
IHTMlement

如果希望返回所有文本,请尝试函数
querySelectorAll
。此函数返回IHTMLDOMChildrenCollection
并接受。嗯


例如:

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate  Website_URL

Do While IE.Busy And Not IE.readyState = READYSTATE_COMPLETE
  DoEvents
Loop
Set Document = IE.Document

Dim SearchValue As String  
Set Element = Document.getElementById(SearchValue).getAttribute("pre")

Range("I1").Select
ActiveCell.FormulaR1C1 = Element
' Add reference to Microsoft Internet Controls (SHDocVw)
' Add reference to Microsoft HTML Object Library

Dim selector As String
' select element with id = SearchValue which has td which has pre
selector = "#" & SearchValue & " td pre" 

Dim onePre As IHTMLElement
Set onePre = doc.querySelector(selector)
If Not onePre Is Nothing Then
    MsgBox "First pre element text: " & onePre.innerText
End If

Dim allPre As IHTMLDOMChildrenCollection
Set allPre = doc.querySelectorAll(selector)

If allPre.Length > 0 Then
    Dim el, text
    For el = 0 To allPre.Length - 1
        text = text & allPre.Item(el).innerText
    Next
    MsgBox "All pre elements text: " & text
End If

ie.Quit