使用Go语言写一个爬取网站图片的程序
时间: 2024-06-08 10:07:56 浏览: 14
好的,以下是使用Go语言编写的爬取网站图片的程序的示例代码:
```go
package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
)
func main() {
// 网页的URL地址
url := "https://www.example.com"
// 发送HTTP GET请求获取网页内容
res, err := http.Get(url)
if err != nil {
fmt.Println("Error: Failed to get the web page")
return
}
defer res.Body.Close()
// 解析HTML内容
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
fmt.Println("Error: Failed to parse the HTML content")
return
}
// 查找所有的图片标签
doc.Find("img").Each(func(i int, s *goquery.Selection) {
// 获取图片的src属性值
src, exists := s.Attr("src")
if exists {
// 判断是否为绝对路径
if strings.HasPrefix(src, "http") {
// 发送HTTP GET请求获取图片内容
res, err := http.Get(src)
if err != nil {
fmt.Println("Error: Failed to get the image")
return
}
defer res.Body.Close()
// 创建文件并保存图片内容
filename := fmt.Sprintf("image_%d.jpg", i)
file, err := os.Create(filename)
if err != nil {
fmt.Println("Error: Failed to create the file")
return
}
defer file.Close()
_, err = io.Copy(file, res.Body)
if err != nil {
fmt.Println("Error: Failed to save the image")
return
}
fmt.Println("Success: Image saved as", filename)
}
}
})
}
```
这个程序使用了Go语言的第三方库"github.com/PuerkitoBio/goquery"来解析HTML内容,然后查找所有的图片标签,并下载图片到本地。你可以将网页的URL地址替换为你想要爬取的网站。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)