python簡單實現爬取小說《天龍八部》,並在頁面本地訪問

來源:互聯網
上載者:User

標籤: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簡單實現爬取小說《天龍八部》,並在頁面本地訪問

聯繫我們

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