[英]Stripping HTML From A String
我嘗試了很多東西,但似乎沒有什么工作正常。 我有一個Access DB,我正在VBA中編寫代碼。 我有一串HTML源代碼,我有興趣剝離所有HTML代碼和標簽,以便我只有純文本字符串,沒有html或標簽。 做這個的最好方式是什么?
謝謝
一種盡可能具有彈性的標記;
with createobject("htmlfile")
.open
.write "<p>foo <i>bar</i> <u class='farp'>argle </zzzz> hello </p>"
.close
msgbox "text=" & .body.outerText
end with
Function StripHTML(cell As Range) As String
Dim RegEx As Object
Set RegEx = CreateObject("vbscript.regexp")
Dim sInput As String
Dim sOut As String
sInput = cell.Text
With RegEx
.Global = True
.IgnoreCase = True
.MultiLine = True
.Pattern = "<[^>]+>" 'Regular Expression for HTML Tags.
End With
sOut = RegEx.Replace(sInput, "")
StripHTML = sOut
Set RegEx = Nothing
End Function
祝你好運,祝你好運。
這取決於html結構的復雜程度以及您希望從中獲取多少數據。
根據您使用正則表達式可能會帶來的復雜性,但是對於復雜的標記,嘗試使用正則表達式從html解析數據就像嘗試用叉子吃湯一樣。
您可以使用htmFile對象將平面文件轉換為可以與之交互的對象,例如:
Function ParseATable(url As String) As Variant
Dim htm As Object, table As Object
Dim data() As String, x As Long, y As Long
Set htm = CreateObject("HTMLfile")
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", url, False
.send
htm.body.innerhtml = .responsetext
End With
With htm
Set table = .getelementsbytagname("table")(0)
Redim data(1 To table.Rows.Length, 1 To 10)
For x = 0 To table.Rows.Length - 1
For y = 0 To table.Rows(x).Cells.Length - 1
data(x + 1, y + 1) = table.Rows(x).Cells(y).InnerText
Next y
Next x
ParseATable = data
End With
End Function
使用早期綁定:
Public Function GetText(inputHtml As String) As String
With New HTMLDocument
.Open
.write "<p>foo <i>bar</i> <u class='farp'>argle </zzzz> hello </p>"
.Close
StripHtml = .body.outerText
End With
End Function
對上述之一的改進...它找到引號和換行符,並用非HTML等價物替換它們。 此外,原始函數有嵌入式UNC引用的問題(即:<\\ server \\ share \\ folder \\ file.ext>)。 它將刪除整個UNC字符串,因為<在開頭和>結尾。 此函數修復了這個問題,因此UNC正確地插入到字符串中:
Function StripHTML(strString As String) As String
Dim RegEx As Object
Set RegEx = CreateObject("vbscript.regexp")
Dim sInput As String
Dim sOut As String
sInput = Replace(strString, "<\\", "\\")
With RegEx
.Global = True
.IgnoreCase = True
.MultiLine = True
.Pattern = "<[^>]+>" 'Regular Expression for HTML Tags.
End With
sOut = RegEx.Replace(sInput, "")
StripHTML = Replace(Replace(Replace(sOut, " ", vbCrLf, 1, - 1), """, "'", 1, -1), "\\", "<\\", 1, -1)
Set RegEx = Nothing
End Function
我發現了一個非常簡單的解決方案。 我目前運行訪問數據庫並使用excel表單來更新系統,因為系統限制和共享驅動器權限。 當我從Access調用數據時,我使用:Plaintext( YourStringHere )這將刪除所有html部分並僅保留文本。
希望這有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.