dqtu14636 2018-07-31 18:31
浏览 52
已采纳

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

I want to download Fantasy Football Data to analyse in Go, but when I try to download from this api page then I get back an empty response, even though the code works for other websites, e.g. this api page

Minimal reproduction, outputs an empty array.

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)
}

The same webpage downloads fine in Python:

import requests
url = "https://fantasy.premierleague.com/drf/bootstrap-static"
r = requests.get(url)
print(r.content)

I don't think it's related to e.g. Ajax calls as viewing the network requests in Chrome doesn't show up any beyond the page load itself

  • 写回答

1条回答 默认 最新

  • duandan1995 2018-07-31 18:40
    关注

    They are doing some sort of validation on the user agent, the following code works:

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题