在Vbscript中编码Microsoft.XmlHttp的字符

时间:2011-06-04 17:03:52

标签: vbscript character-encoding

我正在编写一个vbscript来从网页中提取一些数据,删除一些关键信息并将其写入文件。

目前我的脚本访问页面并将文件内容保存为字符串是:

Set WshShell = WScript.CreateObject("WScript.Shell")
Set http = CreateObject("Microsoft.XmlHttp")

'Load Webpage where address is URL
http.open "GET", URL, FALSE
http.send ""
'Assign webpage contents as a string to variable called Webpage
WEBPAGE = http.responseText

我需要将内容保存为字符串,以便我可以在其上使用正则表达式来提取我需要的内容。

此脚本完美无缺,除非页面包含非标准字符(例如é)。当页面包含这样的内容时,脚本会抛出错误并停止。

我猜这与编码有关,但我无法弄清楚如何修复它。谁能指出我正确的方向?谢谢你们

修改

感谢这里的帮助,我意识到我问了错误的问题!事实证明我正在下载内容很好 - 问题是,之后我试图编辑它并将其写入文件,并且文件格式错误。我有这个:

Set objTextFile = objFSO.OpenTextFile(OutputFile, 8, True,)

将其更改为:

Set objTextFile = objFSO.OpenTextFile(OutputFile, 8, True, -1)

好像已经修好了。多么疯狂的世界,嗯?谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您可能需要在发送

之前设置正确的标题块

例如以下仅是示例。您需要了解这对您的网站来说是什么

   http.open "GET", URL, FALSE
    http.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
    http.SetRequestHeader "Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
    http.SetRequestHeader "Accept-Language", "en-us,en;q=0.5"
    http.SetRequestHeader "Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
    http.send ""

修改

相反,这是怎么回事。它在这里工作正常

Dim XMLHttpReq,URL,WEBPAGE
Const Eacute  = "%C3%89"

Set XMLHttpReq = CreateObject("MSXML2.ServerXMLHTTP")

URL = "http://en.wikipedia.org/wiki/%C3%89"
'Load Webpage where address is URL
XMLHttpReq.Open "GET", URL, False
XMLHttpReq.send ""
'Assign webpage contents as a string to variable called Webpage
WEBPAGE = XMLHttpReq.responseText
WEBPAGE = Replace(WEBPAGE, Eacute, "É")
'Debug.Print WEBPAGE

在这种情况下,E急性以字符串%C3%89返回,如果需要,您可以强制选择任何字符。

<强> EDIT2:

要添加,如果您使用VBScript执行此操作,您可能会发现此方法很有用

Dim XMLHttpReq, URL, WEBPAGE, fso, f
Const Eacute = "%C3%89"
Set XMLHttpReq = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://en.wikipedia.org/wiki/%C3%89"
XMLHttpReq.Open "GET", URL, False
XMLHttpReq.send ""
WEBPAGE = XMLHttpReq.responseText

Save2File WEBPAGE, "C:\Users\osknows\Desktop\test.txt"

Sub Save2File (sText, sFile)
    Dim oStream
    Set oStream = CreateObject("ADODB.Stream")
    With oStream
        .Open
        .CharSet = "utf-8"
        .WriteText sText
        .SaveToFile sFile, 2
    End With
    Set oStream = Nothing
End Sub