Go语言爬虫项目将结果写入MySql数据库
生活随笔
收集整理的這篇文章主要介紹了
Go语言爬虫项目将结果写入MySql数据库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
來源于Google資深工程師深度講解Go語言
package mainimport ("fmt""io/ioutil""net/http" )const url = "http://www.zhenai.com/zhenghun"func main() {//發送get請求resp, err := http.Get(url)if err != nil {panic(err)}//關閉通道defer resp.Body.Close()//判斷狀態if resp.StatusCode != http.StatusOK {fmt.Errorf("StatusCode:%v \n", http.StatusOK)}//輸出結果all, err := ioutil.ReadAll(resp.Body)if err != nil {fmt.Errorf("ReadAll: %s ", err)}fmt.Printf("%s\n",all) }可以將整個html頁面爬取下來
正則表達式處理
package mainimport ("fmt""io/ioutil""net/http""regexp" )//const url = "http://www.baidu.com" const url = "http://www.zhenai.com/zhenghun"func main() {//發送get請求resp, err := http.Get(url)if err != nil {panic(err)}//關閉通道defer resp.Body.Close()//判斷狀態if resp.StatusCode != http.StatusOK {fmt.Errorf("StatusCode:%v \n", http.StatusOK)}//輸出結果all, err := ioutil.ReadAll(resp.Body)if err != nil {fmt.Errorf("ReadAll: %s ", err)}printListCity(all) }// 獲取城市,url const cityListRe = `<a href="(http://www.zhenai.com/zhenghun/[0-9a-z]+)"[^>]*>([^<]*)</a>`func printListCity(contents []byte) {rg := regexp.MustCompile(cityListRe)allSubmatch := rg.FindAllSubmatch(contents, -1)for _, m := range allSubmatch {fmt.Printf("%s\n ", m[1])fmt.Printf("%s\n ", m[2])} }結果
http://www.zhenai.com/zhenghun/zhuhai珠海http://www.zhenai.com/zhenghun/zhumadian駐馬店http://www.zhenai.com/zhenghun/zhuzhou株洲http://www.zhenai.com/zhenghun/zibo淄博http://www.zhenai.com/zhenghun/zigong自貢http://www.zhenai.com/zhenghun/ziyang1資陽http://www.zhenai.com/zhenghun/zunyi遵義將結果存入數據庫
- 注意的是id為自增長的主鍵,不參與golang語言的表結構展示,特別是在插入時,不應該算入在內
總結
以上是生活随笔為你收集整理的Go语言爬虫项目将结果写入MySql数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go语言如何连接数据库
- 下一篇: 成都大熊猫繁育研究基地免票吗