返回信息流我想抓北邮人论坛手机版的内容http://m.byr.cn/board/ParttimeJob
现在数据已经可以抓到了,但是数据库里面没有插入数据,这是为什么啊
我分析要么是数据库语句写错了,要么是__init__函数里面conn和cursor没有初始化,但是如果我在里面初始化了,
self.conn = sqlite3.connect('test.db')
self.cursor = conn.cursor()
就会报错conn没有定义
下面是我的代码
# -*- 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):
conn = sqlite3.connect('123.db')
cursor = conn.cursor()
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]
cursor.execute("insert into forum_data (id ,title, attr) values (?, ?, ?)",(article_id, article_title, article_attr))
print u'第%d页' %page,article_id, article_title, article_attr
else:
self.enable = False
cursor.close()
conn.commit()
conn.close()
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()
这是一条镜像帖。来源:北邮人论坛 / python / #8822同步于 2015/9/27
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
为什么sqlite里面不能插入数据?【新问题】
gqk289
2015/9/27镜像同步10 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
尼玛,又用正则表达式解析html……赶快换beautifulsoup。
而且还是Python2……赶快换Python3。
而且竟然还用thread模块(这是低级模块,是内部使用的,你应该用threading模块)。
而且竟然还用string.atoi,这个函数python2.0就不推荐使用了,你应该用int直接转换,比如int("12345") == 12345
暖神!!!
可是这个问题到底出在哪里啊?
【 在 nuanyangyang 的大作中提到: 】
尼玛,又用正则表达式解析html……赶快换beauti...
主要是有些框架python3不支持,还有好多网上教程是python2的,转化这个是直接在网上搜的 求不吐槽-_-#
【 在 nuanyangyang 的大作中提到: 】
尼玛,又用正则表达式解析html……赶快换beauti...
【 在 gqk289 的大作中提到: 】
: 主要是有些框架python3不支持,还有好多网上教程是python2的,转化这个是直接在网上搜的 求不吐槽-_-#
: 尼玛,又用正则表达式解析html……赶快换beauti...
具体地说,哪个框架呢?可是我的感觉是越来越多的框架都支持python3了,比如django。
而且Python3自带教程的。
scrapy吧 现在刚上手,只求程序能跑通=_=
【 在 nuanyangyang 的大作中提到: 】
【 在 gqk289 的大作中提到: 】
: 主要是...