python爬取糗事百科数据并保存到sqlite中,命令行读出
2017-11-10 23:26
405 查看
import requests import sqlite3 from bs4 import BeautifulSoup class QSBK: def __init__(self): self.page=0 self.items=[] def getItems(self): print('正在读取第'+str(self.page)+'页........') conn=sqlite3.connect('joke.db') cursor=conn.cursor() cursor.execute('create table if not exists jokes (id integer primary key autoincrement,item varchar,zan varchar)') url='http://www.qiushibaike.com/text/page/'+str(self.page) r=requests.get(url).content soup=BeautifulSoup(r,'html.parser').find_all('div',class_='content') soupz=BeautifulSoup(r,'html.parser').find_all('span',class_='stats-vote') i=0 while i<len(soup): if soup[i].span.string is not None: try: self.items.append(soup[i].span.string +'......'+soupz[i].i.string+'赞') sql='insert into jokes (item,zan) values (\''+soup[i].span.string+'\',\''+soupz[i].i.string+'\')' cursor.execute(sql) except: print('程序崩溃正在恢复中...') i+=1 conn.commit() cursor.close() conn.close() def loadPage(self): if len(self.items)<2: self.page+=1 self.getItems() def getOne(self): i=input() if i=='q': conn=sqlite3.connect('joke.db') cursor=conn.cursor() cursor.execute('drop table if exists jokes') cursor.close() conn.close() return else: self.loadPage() print(self.items[0]) del self.items[0] self.getOne() def start(self): print('给你讲笑话,按回车查看新段子,q退出!') self.getOne() spider=QSBK() spider.start()
相关文章推荐
- python 打开sqlite3内存数据库,操作完毕将数据保存到文件数据库
- Android 保存图片到SQLite,读出SQLite中的图片 分类: Android数据存储 2015-03-22 09:59 39人阅读 评论(0) 收藏
- Python MySQL读出数据后保存到文件时中文乱码解决
- HeadFirstPython---------(二)第四章,持久存储,数据保存到文件
- python数据保存加载(numpy)
- SQLite3创建数据库的方法 和 SQLite从Excel文件中导入数据 及 python/qpython sqlite 中文 乱码
- Python备份文件、文件版本的学生管理系统如何实现(将数据保存在txt文件中)
- python中对numpy数组的保存(图像分析image2array后保存数组可用于进一步数据分析)
- 简单Python3爬虫程序(2)进阶:伪装浏览器、超时功能、保存数据
- python(类和对象之保存数据到本地)
- pickle——保存python中数据结构的模块
- 利用python抓取搜狗关于数据分析的文章并保存到csv文件
- Android 保存图片到SQLite,读出SQLite中的图片
- python数据如何保存到excel中
- python保存数据到本地文件的方法
- 将链表中的数据保存到二进制文件和读出数据
- 数据打开【Cocos2D-X 】初窥门径(13)使用 sqlite 保存数据数据打开
- Python读取和处理文件后缀为".sqlite"的数据文件
- Python保存/提取数据的方法
- python中数据的保存