python+mysql抓取百度新闻的标题存到数据库
2016-02-22 16:36
423 查看
#!usr/bin/python # -*- coding:utf-8 -*- import urllib2 import re import MySQLdb class BaiDuNews: def __init__(self): self.baseurl = 'http://news.baidu.com/' def getPage(self): request = urllib2.Request(self.baseurl) response = urllib2.urlopen(request) # print response.read() return response.read().decode('gbk') def getContents(self,page): pattern = re.compile('<li class="hd.*?<a.*?>(.*?)</a>', re.S) items = re.findall(pattern, page) contents = [] for item in items: print item contents.append(item.encode('utf-8')) return contents def saveDB(self, contents): db = MySQLdb.connect(host='127.0.0.1',user='root',passwd='',db='test',charset='utf8') cur = db.cursor() # sql = 'CREATE TABLE baidunews (`id` INT NOT NULL PRIMARY ,`text` VARCHAR(255))' # cur.execute(sql) sql2 = """INSERT INTO baidunews VALUES (NULL ,"%s")""" for content in contents: cur.execute(sql2 % (content)) cur.close() db.commit() db.close() news = BaiDuNews() news.saveDB(news.getContents(news.getPage()))
相关文章推荐
- python随机验证码函数
- Python
- python操作excel文件的方法
- 【python】编程语言入门经典100例--10
- python高级语法
- python zipfile模块测试
- 【python】编程语言入门经典100例--9
- Python 调用 Stanford Parser 两种方法
- An Example Using boto Amazon MWS Package
- python查询数据库并发送邮件
- Python入门-函数的使用到程序的公布安装
- python学习笔记三--字典
- Python 第六篇(上):面向对象编程初级篇
- python成长之路第二篇(4)_collections系列
- python生成器
- python一键打包
- python学习笔记
- 【Python】python读取文件操作mysql
- python string unicode字符串
- python:使用paramiko批量管理服务器(含密钥和密码)