Golang網頁下載樣本

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。


package main/* * 中文編碼問題 */import ("errors""flag""fmt"query "github.com/PuerkitoBio/goquery""golang.org/x/text/encoding/simplifiedchinese""io/ioutil""net/http""os""path/filepath""runtime""strings""sync")var (np = runtime.NumCPU()_  = runtime.GOMAXPROCS(np))var wg sync.WaitGrouptype Folder struct {Url stringDir string}type File struct {Url  stringDir  stringName string}func checkErr(err error) {if err != nil {fmt.Printf("%v\n", err.Error())os.Exit(1)}}func decodeToGBK(text string) (string, error) {dst := make([]byte, len(text)*2)tr := simplifiedchinese.GB18030.NewDecoder()nDst, _, err := tr.Transform(dst, []byte(text), true)if err != nil {return text, err}return string(dst[:nDst]), nil}func printEach(index int, item *query.Selection) {fmt.Println("Selection: ", item.Text())}func isDir(path string) bool {return strings.HasSuffix(path, "/")}func makeFolder(item *query.Selection, url, dir string) (f *Folder, err error) {tx := item.Text()href, ok := item.Attr("href")name, err := decodeToGBK(tx)if err != nil {return}if !ok {err = errors.New("makeFolder : " + tx + " href屬性不存在")return}f = &Folder{Url: url + href, Dir: filepath.Join(dir, name)}return}func makeFile(item *query.Selection, url, dir string) (f *File, err error) {tx := item.Text()href, ok := item.Attr("href")if !ok {err = errors.New("makeFile : " + tx + " href屬性不存在")return}name, err := decodeToGBK(tx)if err != nil {return}f = &File{Url: url + href, Dir: dir, Name: name}return}func crawl(url, localDir string) {doc, err := query.NewDocument(url)// checkErr(err)if err != nil {fmt.Printf("%v\n", err.Error())return}items := doc.Find("a")dir := localDirif !strings.HasSuffix(url, "/") {url += "/"}crawlEach := func(i int, item *query.Selection) {tx := item.Text()if isDir(tx) {folder, err := makeFolder(item, url, dir)if err != nil {fmt.Printf("%v\n", err.Error())return}wg.Add(1)go crawlFolder(folder)} else {file, err := makeFile(item, url, dir)if err != nil {fmt.Printf("%v\n", err.Error())return}download(file)}}items.Each(crawlEach)}func download(file *File) {dir := file.Dirurl := file.Urlname := file.Nameif err := os.MkdirAll(dir, os.ModePerm); os.IsExist(err) {fmt.Printf("%x is exist\n", dir)} else {os.Chmod(dir, os.ModePerm)}resp, err := http.Get(url)if err != nil {fmt.Printf("%v\n", err.Error())return}defer resp.Body.Close()body, err := ioutil.ReadAll(resp.Body)if err != nil {fmt.Printf("%v\n", err.Error())return}fp := string([]rune(filepath.Join(dir, name)))err = ioutil.WriteFile(fp, body, 0777)if err != nil {fmt.Printf("%v fp:[%v]\n", err.Error(), fp)return}fmt.Printf("Download: %+v\n", file)}func crawlFolder(folder *Folder) {url := folder.Urldir := folder.Dircrawl(url, dir)wg.Done()}func main() {host := flag.String("host", "http://localhost:8000", "HTTP服務地址Host")location := flag.String("locate", "E:/Crawler下載檔案", "本地檔案系統絕對路徑")flag.Parse()crawl(*host, *location)wg.Wait()}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.