申明仅供学习
一、准备工作
网站:亿图网爬取美女图(https://www.yeitu.com)
go语言基础
二、爬取美女区域(/meinv/)
先梳理流程(暂不编码)
找到对应的导航栏
复制标签对应的selector
body > div:nth-child(4) > div.yt-title > h3 > a
删除:nth-child(4)保留所需的: body > div > div.yt-title > h3 > a
代码获取到对应的链接后,请求地址(例:https://www.yeitu.com/meinv/xinggan/)
同理找到对应的标签,复制selector
body > div.list_tags.w > div.list_tags_box > a
代码获取对应的地址,拼接上https://www.yeitu.com(例:https://www.yeitu.com/tag/siwameitui/)
请求该地址
找到具体的图片标签,复制selector
tag_box > div > a > img
获取所需美女图片的地址
三、代码爬取
package main
import (
"bufio"
"fmt"
"github.com/gocolly/colly"
"os"
"strconv"
)
func main() {
yeitu()
}
// 亿图网爬取美女图
var baseUrl = "https://www.yeitu.com"
func yeitu() {
var homeUrl = baseUrl + "/meinv/"
fetch1(homeUrl)
}
func fetch1(url string) {
col := colly.NewCollector()
// 检测请求
col.OnRequest(func(req *colly.Request) {
fmt.Println("检测一个请求......")
})
// 检测响应
col.OnResponse(func(r *colly.Response) {
fmt.Println("检测一个响应......")
})
// 定位img标签。注册该函数,框架内部回调
col.OnHTML("body > div > div.yt-title > h3 > a", func(elem *colly.HTMLElement) {
// 获取标签对应属性的值。
attr := elem.Attr("href")
fetch2(attr)
})
col.Visit(url)
}
func fetch2(url string) {
col := colly.NewCollector()
// 检测请求
col.OnRequest(func(req *colly.Request) {
fmt.Println("检测一个请求......")
})
// 检测响应
col.OnResponse(func(r *colly.Response) {
fmt.Println("检测一个响应......")
})
// 定位img标签。注册该函数,框架内部回调
col.OnHTML("body > div.list_tags.w > div.list_tags_box > a", func(elem *colly.HTMLElement) {
// 获取标签对应属性的值。
attr := elem.Attr("href")
fetch3(baseUrl + attr)
})
col.Visit(url)
}
func fetch3(url string) {
col := colly.NewCollector()
// 检测请求
col.OnRequest(func(req *colly.Request) {
fmt.Println("检测一个请求......")
})
// 检测响应
col.OnResponse(func(r *colly.Response) {
fmt.Println("检测一个响应......")
})
// 定位img标签。注册该函数,框架内部回调
col.OnHTML("#tag_box > div > a > img", func(elem *colly.HTMLElement) {
// 获取标签对应属性的值。
attr := elem.Attr("src")
fmt.Println(attr + "\n")
})
col.Visit(url)
}
AI 代码解读
四、优化
可以使用多线程,并且分页爬取,保存的时候按图片分类存储