错误超时获取 HTTP 请求 golang



我试图用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:nn", 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不希望他们的网站上有自动扫描程序\抓取器,并且具有机器人保护机制。以下是他们的建议:

每两秒一个请求

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

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

time.Sleep(6 * time.Second)

最新更新