【发布时间】:2021-06-08 07:50:17
【问题描述】:
我真的是新手,我现在正在通过按照本教程构建一个简单的网络爬虫来玩它: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 或进一步解析。
任何提示都将非常感谢我的学习
【问题讨论】:
标签: go web-crawler url-parsing