1. 程式人生 > >python從零開始寫爬蟲(5)-- 資料入庫

python從零開始寫爬蟲(5)-- 資料入庫

寫好的爬蟲,現在就讓他跑起來,把資料load到資料庫

具體操作:

1.安裝python 連結mysql的庫:pip install PyMySql

2.新建資料庫及表:

DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
  `newsid` varchar(255) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `newssource` varchar(255) DEFAULT NULL,
  `dt` varchar(255) DEFAULT NULL,
  `article` mediumtext,
  `editor` varchar(255) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;

3.操作資料庫方法:
import pymysql 
def connDB(): 
    #連線資料庫 
    conn=pymysql.connect(host='localhost',user='root',passwd='',db='pythod_pacong',charset='utf8') 
    cur=conn.cursor()
    return (conn,cur)

def exeUpdate(conn,cur,sql): 
    #更新語句,可執行Update,Insert語句 
    sta=cur.execute(sql)
    conn.commit()
    return (sta)

def exeQuery(cur,sql): 
    #查詢語句 
    cur.execute(sql)
    result = cur.fetchone()
    return (result)


def connClose(conn,cur): 
    #關閉所有連線 
    cur.close()
    conn.close()

4.開始爬蟲load資料入庫:
connDB1 = connDB()
sql = "insert into news(newsid,title,newssource,dt,article,editor) values"
urls = getNewsURLs('http://news.sina.com.cn/china/')
for url in urls:
    sql1 = sql+ '("'+ getNewsDetail(url)["newsid"] +'","'+getNewsDetail(url)["title"]+'","'+getNewsDetail(url)["newssource"]+'","'+getNewsDetail(url)["dt"]+'","' +getNewsDetail(url)["article"] +'","' + getNewsDetail(url)["editor"]  + '")'
    print(exeUpdate(connDB1[0],connDB1[1],sql1))
connClose(connDB1[0],connDB1[1])

5.爬取結果如下: