mysql和python的链接
来源:互联网 发布:网络女歌手伤感情歌 编辑:程序博客网 时间:2024/05/16 23:33
在学习mysql多看一些官方文档,再加上百度其中有很多。再加上mysql的可视化程序有很多,所以我这个小辣鸡就不献丑了......
这个程序是我在爬完糗事百科之后,就直接拿过来用的。我想把我爬下来的东西,存到数据库中。
# -*- coding: utf-8 -*import reimport urllibimport urllib2import MySQLdbimport sysreload(sys)sys.setdefaultencoding('utf8')for page in range(2,6): url = 'http://www.qiushibaike.com/hot/page/' + str(page) user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent } try: request = urllib2.Request(url,headers = headers) response = urllib2.urlopen(request) content = response.read().decode('utf-8') pattern = re.compile('.*?<h2>\n(.*?)\n</h2>.*?\n.*?<span>\n\n\n(.*?)\n</span>.*?<i class="number">(.*?)</i>.*?(.*?).*?<i class="number">(.*?)</i>',re.S) items = re.findall(pattern,content) for item in items: haveImg = re.search("img",item[3]) if not haveImg: w=re.sub('<br/>',' ',item[1]) print item[0],'|',w,item[2],'|',item[4] conn = MySQLdb.connect( host='127.0.0.1', port=3306, user='账号', passwd='密码', db='数据库名称', charset='utf8', ) cur = conn.cursor() hot = "insert into 糗事百科(名字,正文,评论,好笑) values('%s','%s','%s','%s')" %(item[0],w,item[2],item[4]) print hot cur.execute(hot) conn.commit() #提交数据进数据库 conn.close() #关闭数据库 except urllib2.URLError, e : if hasattr(e,"code"): print e.code if hasattr(e,"reason"): print e.reason
真是明白了不难,不明白就能把你难死...当懂了原理之后就会很简单。
其中要注意的是一定要先在数据库中建立好数据库名称。当然这是入门级别的一个小例子,注意for循环...
阅读全文
0 0
- mysql和python的链接
- python----mysql链接汉字编码的问题
- Python中链接MySql数据库的配置
- Python的mysql操作(安装、链接)
- python链接mysql常见问题
- 使用python链接mysql
- python链接Mysql数据库
- python链接mysql数据库
- python链接mysql
- Python链接Mysql数据库
- Python链接Mysql数据库
- python 链接MySQL数据库
- python链接Mysql数据库
- 获得mysql和oracle链接的类
- sringMVC链接oracle和mysql的字符串
- python mysql使用持久链接
- python链接mysql常见问题汇总
- python链接mysql常见问题汇总
- 搜索引擎选择: Elasticsearch与Solr
- PullToRefresh引入依赖,布局,适配器ListView上拉加载下拉刷新
- java基础-final关键字
- GPU卡的主流调度平台
- 【转】iOS集成 jpush-react-native常见问题
- mysql和python的链接
- hdu1176免费馅饼(数塔问题,动态规划)
- vue.js中使用slot
- c++ fstream操作
- 【TensorFlow】神经网络模型训练及完整程序实例(五)
- Rxjava操作符入门(二)
- 一般函数指针和类的成员函数指针
- git的基本流程
- 读《ML 预测分析核心算法》(2)