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是在最后一次使用。
總結
以上是生活随笔為你收集整理的python无效数据怎么办_Python使用sqlite插入数据无效的原因的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电液伺服系统_电液伺服系统的误差/偏差以
- 下一篇: python霍夫变换检测直线_OpenC