Go语言实战爬虫项目
<div id="output_wrapper_id" class="output_wrapper" style="font-size: 16px; color: rgba(62, 62, 62, 1); line-height: 1.6; word-spacing: 0; letter-spacing: 0; font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif"><h3 id="hgocollygoquery">Go语言爬虫框架之Colly和Goquery</h3>
<blockquote style="line-height: inherit; display: block; padding: 15px 15px 15px 1rem; font-size: 0.9em; margin: 1em 0; color: rgba(129, 145, 152, 1); border-left: 6px solid rgba(220, 230, 240, 1); background: rgba(242, 247, 251, 1); overflow: auto; overflow-wrap: normal; word-break: normal">
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 0">Python爬虫框架比较多有requests、urllib, pyquery,scrapy等,解析库有BeautifulSoup、pyquery、Scrapy和lxml等等,基于Go的爬虫框架是比较强健的,尤其Colly和Goquery是比较强大的工具,其灵活性和 表达性都比较优秀。</p>
</blockquote>
<h3 id="h">网络爬虫</h3>
<blockquote style="line-height: inherit; display: block; padding: 15px 15px 15px 1rem; font-size: 0.9em; margin: 1em 0; color: rgba(129, 145, 152, 1); border-left: 6px solid rgba(220, 230, 240, 1); background: rgba(242, 247, 251, 1); overflow: auto; overflow-wrap: normal; word-break: normal">
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 0">网络爬虫是什么?从本质上讲,网络爬虫的工作原理通过检查web页面的HTML内容和执行某种类型的行动基于内容。通常,抓取暴露的链接,爬虫按照队列的去爬取。我们也可以从当前页面保存数据提取。例如,如果我们的维基百科页面上开始,我们可能保存页面的文本和标题。</p>
</blockquote>
<h3 id="h-1">爬虫的简单算法</h3>
<pre><code class="go language-go hljs" style="overflow-wrap: break-word; margin: 0 2px; line-height: 18px; font-size: 14px; font-weight: normal; word-spacing: 0; letter-spacing: 0; font-family: Consolas, Inconsolata, Courier, monospace; border-radius: 0; color: rgba(169, 183, 198, 1); background: rgba(40, 43, 46, 1); overflow-x: auto; padding: 0.5em; white-space: pre !important; word-wrap: normal !important; word-break: normal !important; overflow: auto !important">initialize Queue<br>enqueue SeedURL<br><br>while Queue is not empty:<br> URL = Pop element from Queue<br> Page = Visit(URL)<br> Links = ExtractLinks(Page)<br> Enqueue Links on Queue<br><span class="hljs-number" style="font-size: inherit; line-height: inherit; margin: 0; padding: 0; color: rgba(174, 135, 250, 1); word-wrap: inherit !important; word-break: inherit !important">12345678</span><br></code></pre>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">Visit和ExtractLinks函数是改变的地方,两个函数的应用都是特定的。我们的爬虫会尽力解释整个WEB的图,就像google一样,或者像Wikipedia一样简单一些。</p>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">随着你使用的用例的增加许多事情会变得复杂起来,许多许多的页面会被抓取,你可能需要一个更尖端的爬虫同时运行,对于更为复杂的页面,你需要一个更强大的HTML解释器。</p>
<h3 id="hcolly">Colly</h3>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">Colly是一个基于Go语言的灵活的爬虫框架,开箱即用,你会获得一些速率限制,并行爬行等支持。<br>Colly基本组件之一是Collector,Collector保持跟踪那些需要被爬取的页面,并且保持回调当页面被爬取的时候。</p>
<h3 id="h-2" style="line-height: inherit; margin: 1.5em 5px 2em 0; font-weight: bold; font-size: 1.3em; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(135deg, rgba(0, 188, 212, 1), rgba(63, 81, 181, 1)); background-color: rgba(63, 81, 181, 1); color: rgba(255, 255, 255, 1); border-left: 10px solid rgba(51, 51, 51, 1); border-radius: 5px; text-shadow: 1px 1px 1px rgba(102, 102, 102, 1); box-shadow: 1px 1px 2px rgba(102, 102, 102, 1)"><span style="font-size: inherit; color: rgba(255, 255, 255, 1); line-height: inherit; margin: 0; padding: 0">一、开始</span></h3>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">创造一个Collector是容易的,但是我们有许多可选项我们可以使用。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c := colly.NewCollector(
// Restrict crawling to specific domains
colly.AllowedDomains("godoc.org"),
// Allow visiting the same page multiple times
colly.AllowURLRevisit(),
// Allow crawling to be done in parallel / async
colly.Async(true),
)
12345678
</pre>
</div>
<p>你可以只有colly.NewCollector(),然后自己添加那些可选项。</p>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">我们也可以使用一些特别的限制让我们的爬虫表现的像一个行为良好的网络公民,Colly添加速率限制是简单的。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.Limit(&colly.LimitRule{
// Filter domains affected by this rule
DomainGlob:"godoc.org/*",
// Set a delay between requests to these domains
Delay: 1 * time.Second
// Add an additional random delay
RandomDelay: 1 * time.Second,
})
12345678
</pre>
</div>
<p> </p>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">某些网页可能对高流量的访问比较挑剔,他会将你断线。通常设置一个延迟维持几秒中就可让你里淘气榜单远一点。</p>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">从这里开始,我们能开始我们的collector通过一个URL种子。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.Visit("https://godoc.org")</pre>
</div>
<h3 id="honhtml" style="line-height: inherit; margin: 1.5em 5px 2em 0; font-weight: bold; font-size: 1.3em; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(135deg, rgba(0, 188, 212, 1), rgba(63, 81, 181, 1)); background-color: rgba(63, 81, 181, 1); color: rgba(255, 255, 255, 1); border-left: 10px solid rgba(51, 51, 51, 1); border-radius: 5px; text-shadow: 1px 1px 1px rgba(102, 102, 102, 1); box-shadow: 1px 1px 2px rgba(102, 102, 102, 1)"><span style="font-size: inherit; color: rgba(255, 255, 255, 1); line-height: inherit; margin: 0; padding: 0">二、OnHTML</span></h3>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">我们有一个好的collector他可以从任意网站开始工作,现在我们希望我们的collector做一些什么的话他需要检查页面以便提取链接和其他的数据。<br>colly.Collector.OnHTML方法允许注册一个回调为当收集器达到页面相匹配的一部分特定的HTML标签说明符。首先,我们可以得到一个回调时当爬虫看到[标记包含一个href链接。]()</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.OnHTML("a", func(e *colly.HTMLElement) {
// Extract the link from the anchor HTML element
link := e.Attr("href")
// Tell the collector to visit the link
c.Visit(e.Request.AbsoluteURL(link))
})
123456</pre>
</div>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">就像和上面看到的一样,在这个回调中你得到一个colly.HTMLElement它包含了匹配到的HTML的数据。<br>现在,我们有一个实际的网络爬虫的开始:我们发现页面上的链接访问,并告诉我们的collector在后续请求访问这些链接。<br>OnHTML是一个功能强大的工具。它可以搜索CSS选择器(即div.my_fancy_class或# someElementId),你可以连接多个OnHTML回调你的收集器处理不同类型的页面。<br>Colly的HTMLElement结构非常有用。除了使用Attr函数获得那些属性之外,还可以提取文本。例如,我们可能想要打印页面的标题:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.OnHTML("title", func(e *colly.HTMLElement) {
fmt.Println(e.Text)
})
123</pre>
</div>
<h3 id="honrequestonresponse" style="line-height: inherit; margin: 1.5em 5px 2em 0; font-weight: bold; font-size: 1.3em; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(135deg, rgba(0, 188, 212, 1), rgba(63, 81, 181, 1)); background-color: rgba(63, 81, 181, 1); color: rgba(255, 255, 255, 1); border-left: 10px solid rgba(51, 51, 51, 1); border-radius: 5px; text-shadow: 1px 1px 1px rgba(102, 102, 102, 1); box-shadow: 1px 1px 2px rgba(102, 102, 102, 1)"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">三、OnRequest / OnResponse</span></h3>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">有些时候你不需要一个特定的HTML元素从一个页面,而是想知道当你的爬虫检索或刚刚检索页面。为此,Colly暴露OnRequest OnResponse回调。<br>所有这些回调将被调用当访问到每个页面的时候。至于如何在符合OnHTML的使用要求。回调被调用的时候有一些顺序:1。OnRequest 2。OnResponse 3。OnHTML 4。OnScraped(在这边文章中没有提及到,但可能对你有用)<br>尤其使用的是OnRequest中止回调的能力。这可能是有用的,当你想让你的collector停止。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.OnHTML("title", func(e *colly.HTMLElement) {
fmt.Println(e.Text)
})
123</pre>
</div>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">在OnResponse,可以访问整个HTML文档,这可能是有用的在某些情况下:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.OnResponse(func(r *colly.Response) {
fmt.Println(r.Body)
})
123</pre>
</div>
<h3 id="hhtmlelement" style="line-height: inherit; margin: 1.5em 5px 2em 0; font-weight: bold; font-size: 1.3em; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(135deg, rgba(0, 188, 212, 1), rgba(63, 81, 181, 1)); background-color: rgba(63, 81, 181, 1); color: rgba(255, 255, 255, 1); border-left: 10px solid rgba(51, 51, 51, 1); border-radius: 5px; text-shadow: 1px 1px 1px rgba(102, 102, 102, 1); box-shadow: 1px 1px 2px rgba(102, 102, 102, 1)"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">四、HTMLElement</span></h3>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">除了colly.HTMLElement的Attr()方法和text,我们还可以使用它来遍历子元素。ChildText(),ChildAttr()特别是ForEach()方法非常有用。<br>例如,我们可以使用ChildText()获得所有段落的文本部分:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.OnHTML("#myCoolSection", func(e *colly.HTMLElement) {
fmt.Println(e.ChildText("p"))
})
123</pre>
</div>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">我们可以使用ForEach()循环遍历一个孩子匹配一个特定的元素选择器:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.OnHTML("#myCoolSection", func(e *colly.HTMLElement) {
e.ForEach("p", func(_ int, elem *colly.HTMLElement) {
if strings.Contains(elem.Text, "golang") {
fmt.Println(elem.Text)
}
})
})
1234567</pre>
</div>
<h3 id="hbringingingoquery" style="line-height: inherit; margin: 1.5em 5px 2em 0; font-weight: bold; font-size: 1.3em; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(135deg, rgba(0, 188, 212, 1), rgba(63, 81, 181, 1)); background-color: rgba(63, 81, 181, 1); color: rgba(255, 255, 255, 1); border-left: 10px solid rgba(51, 51, 51, 1); border-radius: 5px; text-shadow: 1px 1px 1px rgba(102, 102, 102, 1); box-shadow: 1px 1px 2px rgba(102, 102, 102, 1)"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">五、Bringing in Goquery</span></h3>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">Colly的内置HTMLElement对大多数抓取任务都很有用,但是如果我们想对DOM进行特别高级的遍历,我们就必须去别处寻找。 例如,(目前)没有办法将DOM遍历到父元素或通过兄弟元素横向遍历。<br>输入Goquery,“就像那个j-thing,只在Go中”。 它基本上是jQuery。 在Go。 (这很棒)对于你想从HTML文档中删除的任何内容,可以使用Goquery完成。<br>虽然Goquery是以jQuery为模型的,但我发现它在很多方面与BeautifulSoup API非常相似。 所以,如果你来自Python抓取世界,那么你可能会对Goquery感到满意。<br>Goquery允许我们进行比Colly的HTMLElement提供的更复杂的HTML选择和DOM遍历。 例如,我们可能想要找到我们的锚元素的兄弟元素,以获得我们已经抓取的链接的一些上下文:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">dom, _ := qoquery.NewDocument(htmlData)
dom.Find("a").Siblings().Each(func(i int, s *goquery.Selection) {
fmt.Printf("%d, Sibling text: %s\n", i, s.Text())
})
1234</pre>
</div>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">此外,我们可以轻松找到所选元素的父级。 如果我们从Colly给出一个锚标记,并且我们想要找到页面</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">anchor.ParentsUntil("~").Find("title").Text()
1</pre>
</div>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">ParentsUntil遍历DOM,直到找到与传递的选择器匹配的东西。 我们可以使用〜遍历DOM的顶部,然后允许我们轻松获取标题标记。<br>这实际上只是抓住了Goquery可以做的事情。 到目前为止,我们已经看到了DOM遍历的示例,但Goquery也对DOM操作提供了强大的支持 - 编辑文本,添加/删除类或属性,插入/删除HTML元素等。<br>将它带回网络抓取,我们如何将Goquery与Colly一起使用? 它很简单:每个Colly HTMLElement都包含一个Goquery选项,您可以通过DOM属性访问它。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">c.OnHTML("div", func(e *colly.HTMLElement) {
// Goquery selection of the HTMLElement is in e.DOM
goquerySelection := e.DOM
// Example Goquery usage
fmt.Println(qoquerySelection.Find(" span").Children().Text())
})
1234567</pre>
</div>
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">值得注意的是,大多数抓取任务都可以以不需要使用Goquery的方式构建! 只需为html添加一个OnHTML回调,就可以通过这种方式访问整个页面。 但是,我仍然发现Goquery是我的DOM遍历工具带的一个很好的补充。</p>
<h3 id="h-3">实战项目</h3>
<h4 id="h1metalsucks" style="color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0; font-weight: bold; font-size: 1.2em"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">1. metalsucks专辑评论排名信息</span></h4>
<ul style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0 0 0 32px; list-style-type: disc">
<li style="font-size: inherit; color: inherit; line-height: inherit; margin: 0 0 0.5em; padding: 0">
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">代码</p>
</li>
</ul>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">// go get github.com/PuerkitoBio/goquery
// git clonehttps://github.com/golang/net
package main
import (
"fmt"
"log"
"net/http"
"github.com/PuerkitoBio/goquery"
)
func main() {
// 请求html页面
res, err := http.Get("http://metalsucks.net")
if err != nil {
// 错误处理
log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
}
// 加载 HTML document对象
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal(err)
}
// Find the review items
doc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) {
// For each item found, get the band and title
band := s.Find("a").Text()
title := s.Find("i").Text()
fmt.Printf("Review %d: %s - %s\n", i, band, title)
})
}</pre>
</div>
<ul style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0 0 0 32px; list-style-type: disc">
<li style="font-size: inherit; color: inherit; line-height: inherit; margin: 0 0 0.5em; padding: 0">
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">输出</p>
<pre><code class="go language-go hljs" style="overflow-wrap: break-word; margin: 0 2px; line-height: 18px; font-size: 14px; font-weight: normal; word-spacing: 0; letter-spacing: 0; font-family: Consolas, Inconsolata, Courier, monospace; border-radius: 0; color: rgba(169, 183, 198, 1); background: rgba(40, 43, 46, 1); overflow-x: auto; padding: 0.5em; white-space: pre !important; word-wrap: normal !important; word-break: normal !important; overflow: auto !important">Review <span class="hljs-number" style="font-size: inherit; line-height: inherit; margin: 0; padding: 0; color: rgba(174, 135, 250, 1); word-wrap: inherit !important; word-break: inherit !important">0</span>: Darkthrone - Old Star<br>Review <span class="hljs-number" style="font-size: inherit; line-height: inherit; margin: 0; padding: 0; color: rgba(174, 135, 250, 1); word-wrap: inherit !important; word-break: inherit !important">1</span>: Baroness - Gold & Grey<br>Review <span class="hljs-number" style="font-size: inherit; line-height: inherit; margin: 0; padding: 0; color: rgba(174, 135, 250, 1); word-wrap: inherit !important; word-break: inherit !important">2</span>: Death Angel - Humanicide<br>Review <span class="hljs-number" style="font-size: inherit; line-height: inherit; margin: 0; padding: 0; color: rgba(174, 135, 250, 1); word-wrap: inherit !important; word-break: inherit !important">3</span>: Devin Townsend - Empath<br>Review <span class="hljs-number" style="font-size: inherit; line-height: inherit; margin: 0; padding: 0; color: rgba(174, 135, 250, 1); word-wrap: inherit !important; word-break: inherit !important">4</span>: Whitechapel - The Valley<br></code></pre>
</li>
</ul>
<h4 id="h2emojipediacollygoquery" style="color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0; font-weight: bold; font-size: 1.2em"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">2. emojipedia表情抓取(colly + goquery)</span></h4>
<ul style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0 0 0 32px; list-style-type: disc">
<li style="font-size: inherit; color: inherit; line-height: inherit; margin: 0 0 0.5em; padding: 0">
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">代码</p>
</li>
</ul>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">package main
import (
"fmt"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gocolly/colly"
)
func main() {
c := colly.NewCollector(
colly.AllowedDomains("emojipedia.org"),
)
// Callback for when a scraped page contains an article element
c.OnHTML("article", func(e *colly.HTMLElement) {
isEmojiPage := false
// Extract meta tags from the document
metaTags := e.DOM.ParentsUntil("~").Find("meta")
metaTags.Each(func(_ int, s *goquery.Selection) {
// Search for og:type meta tags
property, _ := s.Attr("property")
if strings.EqualFold(property, "og:type") {
content, _ := s.Attr("content")
// Emoji pages have "article" as their og:type
isEmojiPage = strings.EqualFold(content, "article")
}
})
if isEmojiPage {
// Find the emoji page title
fmt.Println("Emoji: ", e.DOM.Find("h1").Text())
// Grab all the text from the emoji's description
fmt.Println(
"Description: ",
e.DOM.Find(".description").Find("p").Text())
}
})
// Callback for links on scraped pages
c.OnHTML("a", func(e *colly.HTMLElement) {
// Extract the linked URL from the anchor tag
link := e.Attr("href")
// Have our crawler visit the linked URL
c.Visit(e.Request.AbsoluteURL(link))
})
c.Limit(&colly.LimitRule{
DomainGlob:"*",
RandomDelay: 1 * time.Second,
})
c.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting", r.URL.String())
})
c.Visit("https://emojipedia.org")
}</pre>
</div>
<ul style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0 0 0 32px; list-style-type: disc">
<li style="font-size: inherit; color: inherit; line-height: inherit; margin: 0 0 0.5em; padding: 0">
<p style="font-size: inherit; color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0">运行结果</p>
</li>
</ul>
<img src="https://img2018.cnblogs.com/common/1476293/201911/1476293-20191122170219428-598928796.png"><br>
<h4 id="h3" style="color: inherit; line-height: inherit; padding: 0; margin: 1.5em 0; font-weight: bold; font-size: 1.2em"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">3.校花网图片爬取</span></h4>
<ul style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0 0 0 32px; list-style-type: disc">
<li style="font-size: inherit; color: inherit; line-height: inherit; margin: 0 0 0.5em; padding: 0"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">代码</span></li>
</ul>
<p> </p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">// 知识点
// 1. http 的用法,返回数据的格式、编码
// 2. 正则表达式
// 3. 文件读写
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/axgle/mahonia"
)
var workResultLock sync.WaitGroup
func check(e error) {
if e != nil {
panic(e)
}
}
func ConvertToString(src string, srcCode string, tagCode string) string {
srcCoder := mahonia.NewDecoder(srcCode)
srcResult := srcCoder.ConvertString(src)
tagCoder := mahonia.NewDecoder(tagCode)
_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
result := string(cdata)
return result
}
func download_img(request_url string, name string, dir_path string) {
image, err := http.Get(request_url)
check(err)
image_byte, err := ioutil.ReadAll(image.Body)
defer image.Body.Close()
file_path := filepath.Join(dir_path, name+".jpg")
err = ioutil.WriteFile(file_path, image_byte, 0644)
check(err)
fmt.Println(request_url + "\t下载成功")
}
func spider(i int, dir_path string) {
defer workResultLock.Done()
url := fmt.Sprintf("http://www.xiaohuar.com/list-1-%d.html", i)
response, err2 := http.Get(url)
check(err2)
content, err3 := ioutil.ReadAll(response.Body)
check(err3)
defer response.Body.Close()
html := string(content)
html = ConvertToString(html, "gbk", "utf-8")
// fmt.Println(html)
match := regexp.MustCompile(`<img width="210".*alt="(.*?)".*src="(.*?)" />`)
matched_str := match.FindAllString(html, -1)
for _, match_str := range matched_str {
var img_url string
name := match.FindStringSubmatch(match_str)
src := match.FindStringSubmatch(match_str)
if strings.HasPrefix(src, "http") != true {
var buffer bytes.Buffer
buffer.WriteString("http://www.xiaohuar.com")
buffer.WriteString(src)
img_url = buffer.String()
} else {
img_url = src
}
download_img(img_url, name, dir_path)
}
}
func main() {
start := time.Now()
dir := filepath.Dir(os.Args)
dir_path := filepath.Join(dir, "images")
err1 := os.MkdirAll(dir_path, os.ModePerm)
check(err1)
for i := 0; i < 4; i++ {
workResultLock.Add(1)
go spider(i, dir_path)
}
workResultLock.Wait()
fmt.Println(time.Now().Sub(start))
}</pre>
</div>
<p> </p>
<ul style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0 0 0 32px; list-style-type: disc">
<li style="font-size: inherit; color: inherit; line-height: inherit; margin: 0 0 0.5em; padding: 0"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">运行结果</span></li>
</ul>
<img src="https://img2018.cnblogs.com/common/1476293/201911/1476293-20191122165553645-1542648048.png"><br>
<ul style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0 0 0 32px; list-style-type: disc">
<li style="font-size: inherit; color: inherit; line-height: inherit; margin: 0 0 0.5em; padding: 0"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0">下载的图片</span></li>
</ul>
<p><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0; padding: 0"><img src="https://img2018.cnblogs.com/common/1476293/201911/1476293-20191122165605114-1717506851.png"></span></p>
</div>
</div>
<div id="MySignature" role="contentinfo">
<div style="border-bottom: #e0e0e0 1px dashed; border-left: #e0e0e0 1px dashed; padding: 10px; font-family: 微软雅黑; font-size: 11px; border-top: #e0e0e0 1px dashed; border-right: #e0e0e0 1px dashed;overflow: hidden;" id="PSignature">
<div style="float: left; width: 10%">
<img src="https://www.cnblogs.com/images/cnblogs_com/zhangyafei/1378866/o_o_Warning.png" style="width: 70px; height: 70px">
</div>
<div style="float: left; width: 90%; padding-top: 10px">
作者:张亚飞 <br>
出处:https://www.cnblogs.com/zhangyafei <br>
gitee:https://gitee.com/zhangyafeii <br>
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。<br>
</div>
</div><br><br>
来源:https://www.cnblogs.com/zhangyafei/p/11912589.html
頁:
[1]