用go语言生成一个爬取视频的爬虫代码
时间: 2023-05-26 10:01:22 浏览: 72
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
)
func main() {
resp, err := http.Get("https://www.example.com") // 替换成目标网站的 URL
if err != nil {
fmt.Println("Error fetching page:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
re := regexp.MustCompile(`<a.*href="(.*\.mp4)"`) // 正则表达式匹配视频文件链接
matches := re.FindAllSubmatch(body, -1)
for _, match := range matches {
url := string(match[1])
fmt.Println("Downloading video from", url)
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error fetching video:", err)
continue
}
defer resp.Body.Close()
video, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading video contents:", err)
continue
}
// 将视频保存到本地文件
err = ioutil.WriteFile("video.mp4", video, 0644)
if err != nil {
fmt.Println("Error writing video to file:", err)
continue
}
fmt.Println("Video saved to video.mp4")
}
}
相关推荐
![](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)
![](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)