首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么Golang不能下载某些网页?

为什么Golang不能下载某些网页?
EN

Stack Overflow用户
提问于 2018-08-01 02:31:32
回答 1查看 60关注 0票数 2

我想下载Fantasy Football的数据,以便在Go中进行分析,但当我尝试从this api page下载时,我得到了一个空响应,即使代码适用于其他网站,例如this api page

最小重现,输出一个空数组。

代码语言:javascript
复制
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

const AllPlayerData = "https://fantasy.premierleague.com/drf/bootstrap-static"

func main() {
    downloadAllData()
}

func downloadAllData() {
    client := &http.Client{
        Timeout: 20 * time.Second,
    }

    response, err := client.Get(AllPlayerData)
    if err != nil {
        fmt.Println("Unable to download player data.")
        return
    }

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("Failed to read response")
        return
    }

    defer response.Body.Close()

    fmt.Println(body)
}

用Python可以很好地下载相同的网页:

代码语言:javascript
复制
import requests
url = "https://fantasy.premierleague.com/drf/bootstrap-static"
r = requests.get(url)
print(r.content)

我不认为这与Ajax calls有关,因为在Chrome中查看网络请求不会在页面加载本身之外显示任何内容

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-01 02:40:46

他们在用户代理上做了一些验证,下面的代码可以工作:

代码语言:javascript
复制
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

const AllPlayerData = "https://fantasy.premierleague.com/drf/bootstrap-static"

func main() {
    downloadAllData()
}

func downloadAllData() {
    client := &http.Client{
        Timeout: 20 * time.Second,
    }

    request, err := http.NewRequest(http.MethodGet, AllPlayerData, nil)
    if err != nil {
        fmt.Println("Unable to create request.")
        return
    }
    request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36")
    response, err := client.Do(request)
    if err != nil {
        fmt.Println("Unable to download player data.")
        return
    }

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("Failed to read response")
        return
    }

    defer response.Body.Close()

    fmt.Println(string(body))
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51619910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档