python2.7 爬蟲_爬取小說盜墓筆記章節及URL並匯入MySQL資料庫_20161201

來源:互聯網
上載者:User

標籤:src   爬取   python   error:   sel   decode   異常   reg   nec   

1、爬取頁面 http://www.quanshu.net/book/9/9055/

2、用到模組urllib(網頁下載),re正則匹配取得title及titleurl,urlparse(拼接完整url),MySQLdb(匯入MySQL) 資料庫

3、for 迴圈遍曆列表 取得盜墓筆記章節title 和 titleurl

4、try except 異常處理

5、python 代碼

#-*-coding: utf-8 -*-import urllibimport reimport urlparseimport MySQLdbrooturl=‘http://www.quanshu.net/book/9/9055/‘def getlist(url):    html=urllib.urlopen(url).read()    html=html.decode(‘gb2312‘).encode(‘utf-8‘)    reg=r‘<li><a href="(.*?)" title=".*?">(.*?)</a></li>‘    return re.findall(reg,html)try:    conn = MySQLdb.connect(host=‘localhost‘, user=‘root‘, passwd=‘123456‘, db=‘local_db‘, port=3306, charset=‘utf8‘)    with conn:        cursor = conn.cursor()        drop_table_sql=‘DROP  TABLE IF EXISTS daomubiji‘        cursor.execute(drop_table_sql)        conn.commit()        create_table_sql = ‘‘‘           CREATE TABLE daomubiji (           ID INT(11),           title VARCHAR(255),           titleurl VARCHAR(255)           )ENGINE=INNODB DEFAULT CHARSET=utf8        ‘‘‘        cursor.execute(create_table_sql)        conn.commit()        urllist = getlist(rooturl)        #href屬性取得的url不完整 僅取出了完整url的右半段 因此下面for迴圈變數名起名righturl        ID=0        for righturl in urllist:            title = righturl[1]            newurl = righturl[0]            #urlparse 模組的urlparse.urljoin方法將righturl 按照rooturl格式拼接成完整url            titleurl = urlparse.urljoin(rooturl, newurl)            ID+=1            print ID,title, titleurl            cursor.execute("INSERT INTO  daomubiji values(%s,%s,%s)", (ID,title, titleurl))            conn.commit()        print "輸入了"+ str(ID) +"條資料"except MySQLdb.Error:    print "串連失敗!"

代碼執行情況:

6、MySQL資料庫查詢是否匯入成功

SELECT * FROM daomubiji

  

 7、執行成功

python2.7 爬蟲_爬取小說盜墓筆記章節及URL並匯入MySQL資料庫_20161201

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.