猿问

Golang“登录网站并下载xls文件”?

告诉我如何使用 Golang 登录站点。下载xls文件是得到了,但是为了在Excel表格中有数据,需要登录网站。该站点位于公司的服务器上。如果你能告诉你怎么做。


例如,我用来执行此操作的 VBA 代码。


Set oFields = CreateObject("Scripting.Dictionary")

With oFields

    .Add "login", "sdiscor"

    .Add "password", "sdiscor"

End With

For Each sName In oFields

    oFields(sName) = sName & "=" & EncodeUriComponent(oFields(sName))

Next

sPayLoad = Join(oFields.Items(), "&")


With CreateObject("MSXML2.XMLHTTP")

    .Open "POST", "http://effect.gvc.oao.rzd/cgi_bin/effect_access.pl?", False

    .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

    .setRequestHeader "Content-Length", LenB(sPayLoad)

    .Send (sPayLoad)


    Do While .readyState <> 4

        DoEvents

    Loop


    webLink = "http://effect.gvc.oao.rzd/effect/table/***&LOGIN=&PASSWORD="

    vLocalFile = ThisWorkbook.Path & "\SIS-Effect.xls"


    .Open "GET", webLink, True

    .Send


    Do While .readyState <> 4

        DoEvents

    Loop


    oResp = .responseBody


    vFF = FreeFile

    If Dir(vLocalFile) <> "" Then Kill vLocalFile

    Open vLocalFile For Binary As #vFF

    Put #vFF, , oResp

    Close #vFF

End With

感谢莱奥拉!!!最终代码


func main() {

urlLogin := "http://effect.gvc.oao.rzd/cgi_bin/effect_access.pl?"

urlDownload := "http://effect.gvc.oao.rzd/effect/table/OZODO10U.XLS?DAT=2019.03.04&LOGIN=&PASSWORD="


cookieJar, _ := cookiejar.New(nil)


client := &http.Client{Jar: cookieJar,}


_, err := client.PostForm(urlLogin,

    url.Values{"login": {"sdiscor"}, "password": {"sdiscor"}})

if err != nil {

    fmt.Println("Error while downloading", urlLogin, "-", err)

    return

}


fileName := "1.xls"

fmt.Println("Downloading", urlDownload, "to", fileName)

output, err := os.Create(fileName)

if err != nil {

    fmt.Println("Error while creating", fileName, "-", err)

    return

}

defer output.Close()


resp, err := client.Get(urlDownload)

if err != nil {

    fmt.Println("Error while downloading", urlDownload, "-", err)

    return

}



叮当猫咪
浏览 95回答 1
1回答

函数式编程

我不知道 VBA,但在我看来你正在使用凭据执行 HTTP POST,然后你正在执行 HTTP GET 以获取你正在寻找的文件。我想您正在使用的类会在请求之间保存 cookie,这就是身份验证的工作方式。假设,在 Go 中,您将使用库https://golang.org/pkg/net/http/cookiejar/来保存 cookie,并使用https://golang.org/pkg/net/http/来执行实际请求.你每次都经过同一个饼干罐。沿着这些线的东西(不准确或检查):package mainimport (&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "net/http/cookiejar")func main() {&nbsp; &nbsp; cookieJar, _ := cookiejar.New(nil)&nbsp; &nbsp; client := &http.Client{&nbsp; &nbsp; &nbsp; &nbsp; Jar: cookieJar,&nbsp; &nbsp; }&nbsp; &nbsp; resp, err := http.PostForm("http://example.com/loginform",&nbsp; &nbsp; &nbsp; &nbsp; url.Values{"login": {"sdiscor"}, "password": {"sdiscor"}})&nbsp; &nbsp; resp, err := client.Get("http://example.com/")}
随时随地看视频慕课网APP

相关分类

Go
我要回答