聽 聽 解析新浪手机新闻网页,获取5条新的新闻的url存入到数据库
package linksql
import (
"database/sql"
"log"
_"github.com/go-sql-driver/mysql"
)
func Open_url_table() *sql.DB{
db,err:=sql.Open("mysql","root:root@/mysql")
Checkerror(err)
return db
}
func Insertlink(id int,src string,url string){
db:=Open_url_table()
stmt,err1:=db.Prepare("insert into url_table(id,src,url) values(?,?,?)")
if err1!=nil{
log.Fatalln("prepare error",err1)
}
_,err2:=stmt.Exec(id,src,url)
if err2!=nil{
log.Fatalln("Exec error")
}
}
func Checkerror(err error){ 聽 //差错
if err!=nil{
log.Fatal(err)
}
}
package search_sina
import (
"net/http"
"log"
"gopkg.in/xmlpath.v2"
"test/linksql"
)
func Get_url(url string){ //找新URL
resp,err:=http.Get(url)
Checkerror(err)
root,err1:=xmlpath.ParseHTML(resp.Body)
Checkerror(err1)
path:=xmlpath.MustCompile(`//dl[@class="f_card"]/../@href`)
iter:=path.Iter(root)
i:=1
for iter.Next() && i<6{
//fmt.Println(iter.Node())
linksql.Insertlink(i,"sina",iter.Node().String())
i++
}
}
func Checkerror(err error){
if err!=nil{
log.Fatalln(err)
}
}
+----+------+-------------------------------------------------------------------------------+ |聽id聽|聽src聽聽|聽url聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽| +----+------+-------------------------------------------------------------------------------+ |聽聽1聽|聽sina聽|聽http://tech.sina.cn/tech_zt/meitu_ipo?vt=4&pos=18聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽| |聽聽2聽|聽sina聽|聽http://tech.sina.cn/i/gj/2016-12-15/detail-ifxytqav9330894.d.html?vt=4&pos=18聽| |聽聽3聽|聽sina聽|聽http://zhuanlan.sina.cn/article?vt=4&pos=18&id=57660&ch=tech聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽| |聽聽4聽|聽sina聽|聽http://tech.sina.cn/i/gj/2016-12-15/detail-ifxytqax6095612.d.html?vt=4&pos=18聽| |聽聽5聽|聽sina聽|聽http://tech.sina.cn/i/gj/2016-12-15/detail-ifxytqav9326149.d.html?vt=4&pos=18聽| +----+------+-------------------------------------------------------------------------------+
有疑问加站长微信联系(非本文作者)