例如,我需要頁面https://aliexpress.ru/item/4001275226820.html 中的內容
在郵遞員和瀏覽器中,我得到頁面的 html 內容
但是當我嘗試使用 GO 時,我無法獲取內容
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://aliexpress.ru/item/4001275226820.html")
defer resp.Body.Close()
if err != nil {panic(err)}
html, err1 := ioutil.ReadAll(resp.Body)
if err1 != nil {panic(err1)}
fmt.Printf("%s\n", html)
}
但是讓恐慌“在 10 次重定向后停止”我做錯了什么?
uj5u.com熱心網友回復:
下面的代碼讓我得到 200 回應。您也許可以簡化它,但應該足以讓您入門:
package main
import (
"fmt"
"net/http"
)
func cookies() ([]*http.Cookie, error) {
req, err := http.NewRequest(
"HEAD", "https://login.aliexpress.ru/sync_cookie_write.htm", nil,
)
if err != nil {
return nil, err
}
val := req.URL.Query()
val.Set("acs_random_token", "1")
req.URL.RawQuery = val.Encode()
res, err := new(http.Transport).RoundTrip(req)
if err != nil {
return nil, err
}
return res.Cookies(), nil
}
func main() {
req, err := http.NewRequest(
"HEAD", "https://aliexpress.ru/item/4001275226820.html", nil,
)
if err != nil {
panic(err)
}
cooks, err := cookies()
if err != nil {
panic(err)
}
for _, cook := range cooks {
if cook.Name == "xman_f" {
req.AddCookie(cook)
}
}
res, err := new(http.Transport).RoundTrip(req)
if err != nil {
panic(err)
}
fmt.Printf("% v\n", res)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343563.html
標籤:走
上一篇:在Go中使用base64.StdEncoding或base64.RawStdEncoding解碼base64字串
