ASP.NET技巧:遠程抓取GOOGLE的自動翻譯結果
2024-07-10 13:09:22
供稿:網友
注冊會員,創建你的web開發資料庫, 1 function removehtml()function removehtml(strhtml)
2 if strhtml<>"" then
3 dim s_str as string
4 s_str=regex.replace(strhtml,"<[^>]+>","")
5 s_str=replace(s_str," ","")
6 return s_str
7 end if
8 end function
9
10 function china_to_english()function china_to_english(texts,languages)
11 dim payload as string = "hl=zh-cn&ie=utf8&text="& texts &"&langpair="& languages &""
12 dim str_return as string
13 dim req as webrequest = webrequest.create("http://translate.google.com/translate_t") ' 開始取連接.
14 req.credentials = credentialcache.defaultcredentials '取得默認
15 req.method = "post" '以post方式發送,這里默認是以get方式發送
16 req.contenttype = "application/x-www-form-urlencoded" 'post方式需在傳送這個編碼,如果上傳文件,則修為multipart/form-data
17 req.timeout=10000 '連接超時定時
18 req.contentlength = payload.length '頭部長度
19 dim encoding as encoding = encoding.getencoding("utf-8") '轉換成流,大部網站一般轉換成utf-8就可以了,注意是大寫的編碼
20 dim bytes as byte() = encoding.getbytes(payload) '轉換成流
21 req.contentlength = bytes.length '傳送流的長度
22 dim newstream as stream = req.getrequeststream() '轉換寫入
23 newstream.write(bytes, 0, bytes.length) '寫入傳送流
24 newstream.close() '關閉
25 '上面發送完成,下面取得服務器返回
26 dim res as httpwebresponse = ctype(req.getresponse(), httpwebresponse) ' 傳遞返回標識
27 if res.statusdescription="ok" then ' 返回取得狀態.
28 current.response.write("暫時無法連接到網站,請換用另一個程序")
29 current.response.end()
30 end if
31 dim datastream as stream = res.getresponsestream() ' 返回給指針
32 dim reader as new streamreader(datastream,encoding.getencoding("gb2312")) ' 讀
33 dim responsefromserver as string = reader.readtoend() ' 讀取所有
34
35 str_return=responsefromserver '賦值回傳
36
37 reader.close() '接下來三個關閉
38 datastream.close()
39 res.close()
40
41 dim ss as string = str_return
42 ss = regex.replace(ss,"(?i:(.+)(/<div)(.+)(/>)(.+)(/<//div/>)(.+))","$5") '提取我們所要的譯文
43 ss = removehtml(ss) '刪除html
44 ss = ss.substring(3) '刪除翻譯二字
45 return ss '函數返回
46 end function
47
48 在調用china_to_english(texts,languages)需要傳兩個參數第一個為要譯的文字,第二個是要進行相對譯的語種代碼.
例:中譯英,其第二個參數為:zh-cn|en
我導入的命名空間如下:
imports system
imports system.web
imports system.io
imports microsoft.visualbasic
imports system.web.httpcontext
imports system.web.ui
imports system.web.ui.webcontrols
imports system.text
imports system.text.regularexpressions
imports system.net