閒來無聊,在網上按照教程寫了一個Python爬蟲,就是竊取數據然後保存下來爬蟲實戰–糗事百科。從糗百上爬取段子,然後輸出到console,我改了一下保存到了數據庫。
不扯沒用的,直接上代碼:
這是爬取得部分
#!/usr/bin/python
# -*- coding:utf-8 -*-
import urllib
import urllib2
import re
import thread
import time
import QsbkDb
class QSBK:
def __init__(self):
self.db = QsbkDb.CQsbkDb("database", "user", "password")
self.db.connect_db()
self.pageIndex = 1
self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
self.headers = {'User-Agent' :self.user_agent}
def __del__(self):
self.db.close_db()
def getPage(self,pageIndex):
try:
url = 'http://www.qiushibaike.com/hot/page/' + str(pageIndex)
request = urllib2.Request(url,headers=self.headers)
response = urllib2.urlopen(request)
pageCode = response.read().decode('utf-8')
return pageCode
except urllib2.URLError,e:
if hasattr(e,"reason"):
print "error",e.reason
if hasattr(e, "code"):
print "code",e.code
return None
def getPageItems(self,pageIndex):
pageCode = self.getPage(pageIndex)
if not pageCode:
print "page load error"
return None
pattern = re.compile('h2>(.*?)</h2.*?content">(.*?)</.*?number">(.*?)</',re.S)
items = re.findall(pattern,pageCode)
pageStories = []
for item in items:
pageStories.append([item[0].strip(),item[1].strip(),item[2].strip()])
return pageStories
def insert_db(self, author, support, context):
_command = 'insert into Jokes(author,support, context)values(\'%s\', %d, \'%s\')'%(author, int(support), context)
#print _command
self.db.execute_db(_command)
def cawler(self):
self.db.execute_db('truncate table Jokes')
for index in range(1,36):
pageStore = self.getPageItems(index)
if pageStore == None:
print "Load page "+ str(index) +" failure\r\n"
continue
for store in pageStore:
page = index
try:
#print u"第%d頁\t發佈人:%s\t 贊:%s\n%s\r\n" %(page,store[0],store[2],store[1])
self.insert_db(store[0], store[2], store[1])
except Exception as e:
print "reson",e.message
del pageStore
time.sleep(1) #這個地方一定不要幹掉
time.sleep(1)睡一下不是白睡的,如果不加這個服務器會作出判斷,認爲你是DDOS攻擊(因爲我們一直在request),有的網站會這樣,而有的網站則不會。
這是數據庫操作部分:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import MySQLdb
class CQsbkDb:
def __init__(self, name, user, passwd):
self.db_name = name
self.db_usr = user
self.db_psw = passwd
def connect_db(self):
self.db_connect = MySQLdb.connect("localhost", self.db_usr, self.db_psw, self.db_name, charset='utf8')
self.db_connect.select_db('qsbk') #你存放糗百的數據庫
def close_db(self):
self.db_connect.close()
def execute_db(self, command):
_cursor = self.db_connect.cursor()
try:
_cursor.execute(command)
self.db_connect.commit()
_cursor.close()
except Exception as e:
print e.message
self.db_connect.rollback()
lz用的是mysql數據庫,數據庫的操作網上一抓一大把,我就不多說了。
先說一下表的結構:
名字叫做 Jokes:
key是插入的編號num,設置爲auto_increment自增模式,所以我們可以看見在QSBK中insert_db函數中num項爲空,它會自己設置不用管。
num: 段子編號 key
author: 作者
support: 點贊數
context:段子內容
這裏面有個需要注意的問題就是建表的時候你要讓author和context支持中文gbk。
alter table Jokes modify context text character set gbk;
alter table Jokes modify author text character set gbk;
以上基本就是這些了,目前僅支持文本段子,不支持圖片。
運行結果: