Excel / 使用SeleniumBasic查詢發佈到網路的google sheets 2

在前一篇Excel / 使用SeleniumBasic查詢發佈到網路的google sheets提到

SeleniumBasic不能將透過模擬鍵盤ctrl+a ctrl+c 將資料貼入Excel

爬文的過程,看到有人建議可以引用Microsoft Forms DataObject的剪貼簿功能

As I said in the comments, Selenium can use SendKeys for this. However, if you should really need the copy-paste action, I suggest using the Clipboard instead.

實際測試時,雖然可以抓到資料並貼回Excel

但是都是純文字的格式

所以一直在測試是不是paste、pastespecial的參數設定問題

例如:有人提到剪貼簿物件要用worksheet物件的方法來貼上

You are using Range.PasteSpecial, which applies to pasting Excel Formatted Range Objects - documentation found here. Unfortunately, what sits on your Clipboard isn't an Excel Range Object, so you need the Worksheet.PasteSpecial method instead.

但是依照這個方式設定.PasteSpecial Format:=”Text”, Link:=False, DisplayAsIcon:= False

還是會產生錯誤

後來在〈Excel VBA 經典程式碼─一行抵萬行「偷懶程式碼」應用大全〉P17-70的範例得知

其實只要有著完整的<table>…</tabe>格式,就能夠將html表格透過剪貼簿貼入Excel裡

所以,透過SeleniumBasic要取得的資料不是文字內容 Text

反而應該是包含完整Html標籤的 outerHtml

在SeleniumBasic取得outerHtml的方式為 .Attribute(“outerHTML”)

.FindElementByCss(  ).Attribute("outerHTML")

所以最終的程式碼擷取重要內容如下

在取得網頁目標table資料並透過Attribute(“outerHTML”)取得完整的table標籤內容

將資料傳入MSForms.DataObject

再透過其中的 SetText( )、PutInClipboard( )、GetFromClipboard( )、GetText( )

tt = BOT.FindElementByCss("css選擇器").Attribute("outerHTML")
Dim DataObj As MSForms.DataObject           '前期繫結 Microsoft Form 2.0 Library
Set DataObj = New MSForms.DataObject        '宣告 MSForms.DataObject

With DataObj
   .SetText ""                  '先清空DataObj內容
   .SetText tt                  '設定內容
   .PutInClipboard              '將資料從DataObj傳入剪貼簿
End With

DataObj.GetFromClipboard     'DataObj取得剪貼簿內容
getStr = DataObj.GetText(1)  '1表示取得文字格式的資料

' MsgBox getStr
' DataObj.GetText(1)          '如果沒有要輸出訊息的話  可以不用回傳到getStr

Sheets(1).Range("A1").Select

ActiveSheet.Paste

With DataObj                  '再清空DataObj內容
   .SetText ""
   .PutInClipboard
End With

 

備註:

使用這個方法的缺點是不能同時操作複製功能

不然程式會被干擾,會被同時進行的複製取代內容

DataObject 的運作方式類似剪貼簿。 如果您將文字字串複製到 DataObject, DataObject 會儲存文字字串。 
如果您將相同格式的第二個字串複製到 DataObject,則 DataObject 會捨棄第一個文字字串,並儲存第二個字串的副本。 
它會儲存指定之格式的一段文字,並保留最近一次作業的文字。

參考資料

Pasting text into Excel using Selenium

VBA Copy to Clipboard, Paste and Clear

Unable to paste special from clipboard

innerHTML、outerHTML、innerText、outerText的區別及相容性問題

〈Excel VBA 經典程式碼─一行抵萬行「偷懶程式碼」應用大全〉,P17-70。

VBA automation can’t get innerText (innerHTML, value)

Selecting inner text when using find element by css selector python, selenium and create a loop

DataObject 物件