標籤: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