忽略go网络爬虫中的外部链接



我真的是新手,现在我正在按照本教程构建一个简单的网络爬虫来使用它:https://jdanger.com/build-a-web-crawler-in-go.html

它分解得很好,但我想把一些东西放在适当的位置,这样唯一排队的链接就是主域的一部分,而不是外部的。

假设我在爬行https://www.mywebsite.com,我只想包括以下内容https://www.mywebsite.com/about-us或https://www.mywebsite.com/contact-我不想要子域,例如https://subdomain.mywebsite.com或外部链接https://www.facebook.com因为我不想让爬行者掉进黑洞里。

查看代码,我认为我需要对这个修复相关链接的函数进行更改:

func fixUrl(href, base string) (string) {  // given a relative link and the page on
uri, err := url.Parse(href)              // which it's found we can parse them
if err != nil {                          // both and use the url package's
return ""                              // ResolveReference function to figure
}                                        // out where the link really points.
baseUrl, err := url.Parse(base)          // If it's not a relative link this
if err != nil {                          // is a no-op.
return ""
}
uri = baseUrl.ResolveReference(uri)
return uri.String()                      // We work with parsed url objects in this
}                                          // func but we return a plain string.

然而,我不能100%确定如何做到这一点,我假设需要某种if/else或进一步的解析。

任何提示都将非常感谢我学习

我很快阅读了jdanger教程并运行了完整的示例。毫无疑问,有几种方法可以实现你想做的事情,但以下是我的看法。

您基本上希望而不是将域与某个指定域不匹配的任何URL排入队列,可能是作为命令行参数提供的。该示例使用fixUrl()函数来构造完整的绝对URL,并通过返回""来发出无效URL的信号。在该函数中,它依赖于net/url包进行解析等,特别是依赖于URL数据类型。URL是具有以下定义的struct

type URL struct {
Scheme      string
Opaque      string    // encoded opaque data
User        *Userinfo // username and password information
Host        string    // host or host:port
Path        string    // path (relative paths may omit leading slash)
RawPath     string    // encoded path hint (see EscapedPath method); added in Go 1.5
ForceQuery  bool      // append a query ('?') even if RawQuery is empty; added in Go 1.7
RawQuery    string    // encoded query values, without '?'
Fragment    string    // fragment for references, without '#'
RawFragment string    // encoded fragment hint (see EscapedFragment method); added in Go 1.15
}

需要注意的是HostHost是URL的"whatever.com"部分,包括子域和端口(有关更多信息,请参阅这篇维基百科文章(。进一步阅读文档,有一种方法Hostname()将剥离端口(如果存在(。

因此,尽管可以将域过滤添加到fixUrl()中,但在我看来,更好的设计是先"修复"URL,然后对结果进行添加检查,以查看其Host是否与所需域匹配。如果不匹配,请不要将URL排入队列,然后继续到队列中的下一个项目。

所以,基本上我认为你走在了正确的轨道上。我还没有包含一个代码示例来鼓励您自己解决这个问题,尽管我确实将您的功能添加到了教程程序的本地副本中。

最新更新