【问题标题】:Error timeout get HTTP request golang错误超时获取HTTP请求golang
【发布时间】:2017-02-10 20:36:19
【问题描述】:

我尝试使用 Golang 从Reddit 获取 html 源代码:

package main

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

func main() {
    timeout := time.Duration(5 * time.Second)
    client := http.Client{
        Timeout: timeout,
    }
    resp, _ := client.Get("https://www.reddit.com/")
    bytes, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("HTML:\n\n", string(bytes))
    defer resp.Body.Close()
    var input string
    fmt.Scanln(&input)
}

第一次尝试很好。但是第二次就报错了:

<p>we're sorry, but you appear to be a bot and we've seen too many requests
from you lately. we enforce a hard speed limit on requests that appear to come
from bots to prevent abuse.</p>

<p>if you are not a bot but are spoofing one via your browser's user agent
string: please change your user agent string to avoid seeing this message
again.</p>

<p>please wait 6 second(s) and try again.</p>

    <p>as a reminder to developers, we recommend that clients make no
    more than <a href="http://github.com/reddit/reddit/wiki/API">one
    request every two seconds</a> to avoid seeing this message.</p>

我尝试设置延迟,但仍然无法正常工作。 对不起我的英语不好。

【问题讨论】:

  • reddit 的回复似乎很容易理解。读两遍。

标签: go


【解决方案1】:

Reddit 不希望在他们的网站上出现自动扫描器\抓取器,并且有一个机器人保护机制。 这是他们的建议:

每两秒一个请求

只需在请求之间添加延迟。

【讨论】:

  • 我设置了超时。但它仍然不起作用 timeout := time.Duration(5 * time.Second) client := http.Client{ Timeout: timeout, }
  • 不是超时,而是延迟。尝试在Get之前添加time.Sleep(2000 * time.Millisecond)
【解决方案2】:

timeout 有不同的用途。 timeout 是例程运行的上限。您需要的是后续请求之间的sleep

time.Sleep(6 * time.Second)

【讨论】:

  • 我在 Get 和 ReadAll 下添加了 time.Sleep 但还是不行
  • 我已经修改了一些位,这段代码对我来说很好:play.golang.org/p/DskqvYB_9B
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 2016-08-15
相关资源
最近更新 更多