使用爬虫时,将数据爬下来之后进行插入操作,但是查看数据库的时候发现并没有任何数据插入。查看被插入数据的格式和内容时机都已经被抓下来了,搜索了很久没有找到答案,最终还是在stackoverflow上面找到了答案,教训就是:
要学会用英文搜索Google!!!
要学会用stackoverflow!!!
Google大法好,stackoverflow大法好!!!
代码如下:
# -*- coding: utf-8 -*-
import urllib,urllib2,re,time,thread,sqlite3,string
class Spider_Model:
def __init__(self):
self.page = 1
self.pages = []
self.enable = False
self.conn = None
self.cursor = None
def GetPage(self,page):
myUrl = "http://m.byr.cn/board/ParttimeJob"+"?p="+page
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
req = urllib2.Request(myUrl, headers = headers)
myResponse = urllib2.urlopen(req)
myPage = myResponse.read()
unicodePage = myPage.decode("utf-8")
myItems = re.findall('<li.*?><div><a href="(.*?)">(.*?)</a>',unicodePage,re.S)
items = []
for item in myItems:
if not item[0].find('class')>=0:
items.append([item[0],item[1]])
return items
def LoadPage(self):
while self.enable:
if len(self.pages)<2:
try:
myPage = self.GetPage(str(self.page))
self.page += 1
self.pages.append(myPage)
except BaseException,e:
print e
else:
time.sleep(1)
def ShowPage(self,nowPage,page):
self.conn = sqlite3.connect('123.db')
self.cursor = self.conn.cursor()
self.cursor.execute('create table if not exists forum_data (id INTEGER primary key UNIQUE, title varchar(20), attr varchar(20))')
for items in nowPage:
if page<=3:
attr = items[0].split('ParttimeJob/')
article_id = string.atoi(attr[1])
article_title = items[1]
article_attr = 'http://m.byr.cn/article/ParttimeJob/'+attr[1]
self.cursor.execute("insert into forum_data (id ,title, attr) values (?, ?, ?)",(article_id, article_title, article_attr))
self.conn.commit()
print u'第%d页' %page,article_id, article_title, article_attr
else:
self.cursor.close()
self.conn.close()
self.enable = False
break
def Start(self):
self.enable = True
page = self.page
print u'正在加载请稍后'
thread.start_new_thread(self.LoadPage,())
while self.enable:
if self.pages:
nowPage = self.pages[0]
del self.pages[0]
self.ShowPage(nowPage,page)
page += 1
print u'请按下回车浏览今日的论坛内容:'
raw_input(' ')
myModel = Spider_Model()
myModel.Start()
1、在类中的函数要使用初始化的函数中的对象时,要在前面加self.conn,self.cursor。
2、在每次插入数据后,要使用self.commit进行提交,而不是最后一并在提交,只有close是在最后一次使用。