標籤:www 技術 color html sqli sql strong tab 流程
寫在前面:第一次使用爬蟲,甚至都算不上爬蟲,水平有限,主要作為學習記錄。
主要商務程序如下:
使用python的requests模組擷取頁面資訊
通過re模組(Regex)取出需要的內容(小說標題,本文)
通過MysqlDB模組入庫
使用webpy模組進行訪問
下面是,簡單實現了點擊上一頁、下一頁翻頁的功能:
目錄結構如下:
D:\PROJECT\SPIDER
│ fiction_spider.py
│ webapp.py
│
└─template
index.html
爬取資訊及入庫代碼如下:
#coding:utf-8
#fiction_spider.pyimport requestsimport reimport MySQLdbdef get_title(): html = requests.get(‘http://www.jinyongwang.com/tian/‘).content rem = r‘<li><a href="(.*?)">(.*?)</a>‘ return re.findall(rem,html)def get_content(url): html = requests.get(‘http://www.jinyongwang.com/‘+url).content #print html matchs_p = r‘<p>(.*?)</p><script.*?‘ data = re.findall(matchs_p, html) return data[0]if __name__ == ‘__main__‘: a = MySQLdb.connect(host=‘10.1.*.*‘, port=3306, user=‘user‘, passwd=‘passwd‘, db=‘testdb‘, charset=‘utf8‘) for i in get_title(): cur = a.cursor() print i[1] print i[0] sqli = ‘INSERT INTO `fiction` (`title`, `content`) VALUES ("%s","%s" )‘%(i[1],get_content(i[0])) cur.execute(sqli) cur.close() a.commit() a.close()
頁面代碼如下:
#coding:utf-8
#webapp.pyimport webimport reurls = (‘/(.*)‘,‘Index‘)db = web.database(dbn = ‘mysql‘,host=‘10.1.*.*‘, port=3306, user=‘user‘, passwd=‘passwd‘, db=‘testdb‘, charset=‘utf8‘)render = web.template.render(‘template‘)class Index: def GET(self,html): id = re.findall(‘(.*?).html‘,html)[0] print id data = db.query("select * from fiction where id=%s"%id) return render.index(data[0],id)if __name__ == ‘__main__‘: web.application(urls,globals()).run()
頁面訪問的index.html內容如下:
$def with(data,s)<meta charset="utf-8"/><title>$:data.title</title><h1>$:data.title</h1><div style="margin:0px auto;text-align:center;"><a href="$:(int(s)-1).html">上一頁</a><a href="$:(int(s)+1).html">下一頁</a></div>$:data.content<br><div style="margin:0px auto;text-align:center;"><a href="$:(int(s)-1).html">上一頁</a><a href="$:(int(s)+1).html">下一頁</a></div>
python簡單實現爬取小說《天龍八部》,並在頁面本地訪問