忽略go网络爬虫中的外部链接
时间:2024-02-11
浏览:355
作者:佚名
珍惜时间,勤奋学习!今天给大家带来《忽略go网络爬虫中的外部链接》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!
我真的很陌生,目前我正在按照本教程构建一个简单的网络爬虫来使用它: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 data type。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
}
需要注意的是 host。 host 是 url 的“whatever.com”部分,包括子域和端口(请参阅 this wikipedia article for more info)。进一步阅读文档,有一个方法 hostname() 它将剥离端口(如果存在)。
因此,虽然您可以向 fixurl() 添加域过滤,但在我看来,更好的设计是首先“修复”url,然后对结果进行附加检查查看其 host 是否与所需的域匹配。如果不匹配,则不要将该 url 排入队列并继续处理队列中的下一项。
所以,基本上我认为你走在正确的道路上。尽管我确实将您的功能添加到了本教程程序的本地副本中,但我没有提供代码示例来鼓励您自行解决。
好了,本文到此结束,带大家了解了《忽略go网络爬虫中的外部链接》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
