python无效数据怎么办_Python使用sqlite插入数据无效的原因

使用爬虫时,将数据爬下来之后进行插入操作,但是查看数据库的时候发现并没有任何数据插入。查看被插入数据的格式和内容时机都已经被抓下来了,搜索了很久没有找到答案,最终还是在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('

(.*?)',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是在最后一次使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值