用python写的一个wordpress的采集程序


Posted in Python onFebruary 27, 2016

在学习python的过程中,经过不断的尝试及努力,终于完成了第一个像样的python程序,虽然还有很多需要优化的地方,但是目前基本上实现了我所要求的功能,先贴一下程序代码:

用python写的一个wordpress的采集程序

具体代码如下:

#! /usr/bin/python
 import os,urllib2,re,time,MySQLdb,sys
 reTitle          = re.compile('<font[^>]*>(.*?)<\/font><font[^>]*')
 reNeiron         = re.compile('[1-9|A-Z|a-z].*')
 retiqu          = re.compile('^(?!MARGINWIDTH|BR).*.[^>|}]$')
 rezhong          = re.compile('^[^[].*')
 shijian=1190944000
 Str1="\\n---------------- BLOG OF YAO"
 bianhao=2859
 for i in range(1,1500):
     Str2=""
     ltime=time.localtime(shijian)
     timeStr=time.strftime("%Y%m%d",ltime)
     url="http://www.jokeswarehouse.com/cgi-bin/viewjoke2.cgi?id=%s" %timeStr
     print url
     a=urllib2.urlopen(url).read()
     Title=reTitle.findall(a)
     print "=========================================================================================================="
     for titles in map(None,Title):
         titles=MySQLdb.escape_string(titles)
         print titles
     Neiron=re.findall(reNeiron,a)
     for i in map(None,Neiron):
         x=re.findall(retiqu,i)
         for str in x:
             str=MySQLdb.escape_string(str)
             Str2 += str+"\\n"
     shijian += 86400
     bianhao += 1
     try:
         conn=MySQLdb.connect("XXXX.XXXX.XXXX.XXXX","user","passwd","dbname",charset="utf8", init_command="set names utf8")
     except MySQLdb.OperationalError,message:
         print "like error"
     cursor=conn.cursor()
     sql="INSERT INTO wp_posts (post_author,post_date,post_date_gmt,post_content,post_content_filtered,post_title,post_excerpt,post_status,post_type,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_parent,menu_order,guid) VALUES (\'1\',\'2011-06-01 22:12:25\',\'2011-05-09 04:12:25\',\'\',\'\',\'Auto Draft\',\'\',\'inherit\',\'revision\',\'open\',\'open\',\'\',\'100-revision\',\'\',\'\',\'2011-06-01 22:12:25\',\'2011-05-09 04:12:25\',\'%s\',\'0\',\'\')" %bianhao
     sql2="UPDATE wp_posts SET post_author = 1, post_date = \'2011-06-01 22:12:25\', post_date_gmt = \'2011-06-01 22:12:25\', post_content =\'%s\', post_content_filtered = \'\', post_title = \'%s\', post_excerpt = \'\', post_status = \'publish\', post_type = \'post\', comment_status = \'open\', ping_status = \'open\', post_password = \'\', post_name = \'%s\', to_ping = \'\', pinged = \'\', post_modified = \'2011-06-01 22:12:25\', post_modified_gmt = \'2011-05-09 04:12:30\', post_parent = 0, menu_order = 0, guid = \'http://www.moncleronlineshops.com/?p=%s\' WHERE ID = %s" %(Str2,titles,titles,bianhao,bianhao)
     cursor.execute(sql)
     cursor.execute(sql2)
     cursor.close()
     conn.close()
     sys.exit()

下面,我们来给代码加些注释,让读者能看的更明白一些,如下:

具体代码如下

#! /usr/bin/python
 import os,urllib2,re,time,MySQLdb,sys #加载本程序需要调用的相模块
reTitle          = re.compile('<font[^>]*>(.*?)<\/font> <font[^>]*') # 定义一下取文章标题的正则
reNeiron         = re.compile('[1-9|A-Z|a-z].*') 
 #定义一个取提取文章内容的正则(注:这里提取出来的不是很精细,需要在下面的正则里,再进行提取,这里只是取一个大概)
retiqu          = re.compile('^(?!MARGINWIDTH|BR).*.[^>|}]$')
 #这里定义一个正则,将上面reNeiron提取出来的字符,再进行细化。

shijian=1190944000  #这里字义了一个时间戳,
Str1="\\n---------------- BLOG OF YAO" #这个没用,开始是准备加到文章里的,后来没加进去。
bianhao=2859   #这里是wordpress 的文章编号,直接查看wp-posts表的id 字段的最后一个数字。

for i in range(1,1500): #循环1500遍,也就是采集1500篇文章。
    Str2="" #先赋值给Str2 空值
    ltime=time.localtime(shijian)  
     timeStr=time.strftime("%Y%m%d",ltime) #这两句将上面的时间戳改为时间,样式为19700101这样的格式
    url="http://www.jokeswarehouse.com/cgi-bin/viewjoke2.cgi?id=%s" %timeStr #定义要采集的网站,将转化后的时间放在这个url的最后。
    a=urllib2.urlopen(url).read() #将这个网页的源代码读出来,赋值给a;
     Title=reTitle.findall(a)
 #使用 reTitle这个正则提取出标题
    print "=========================================================================================================="
     for titles in map(None,Title): #上面提取出来的标题前后都有一个 [] 
所以我们要写个for循环把前后的[]去掉,并转义成能直接插入mysql库的格式。
        titles=MySQLdb.escape_string(titles)
     Neiron=re.findall(reNeiron,a) #先用reNeiron,取个大概的内容模型出来。这些都是以逗号分隔的数组。
    for i in map(None,Neiron): # 我们来循环读出Neiron这个数组里的每个值。
        x=re.findall(retiqu,i)#并用 retiqu这个正则提出精细出的内容。
        for str in x:
             str=MySQLdb.escape_string(str)
             Str2 += str+"\\n"
 #利用这个循环,我们把内容加到一起,并赋值给Str2这个变量,这个 Str2这个变量就是所有的文章内容。
    shijian += 86400 #每循环一次,就把shijian这个变量加上一天。
    bianhao += 1   #每循环一次,就把bianhao这个变量加上一
    try:
 #下面是用mysqldb连接数据库,并尝试连接是否成功。       conn=MySQLdb.connect("XXXX.XXXX.XXXX.XXXX","user","passwd","dbname",charset="utf8", init_command="set names utf8")
     except MySQLdb.OperationalError,message:
         print "like error"
     cursor=conn.cursor()
 #下面是插入wordpress数据库的两条语句,我是从mysqlbinlog里面导出来的,测试是可以插入数据库,并能正常把内容显示在网页的。变量都写在这两条语句里。
    sql="INSERT INTO wp_posts (post_author,post_date,post_date_gmt,post_content,post_content_filtered,post_title,post_excerpt,post_status,post_type,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_parent,menu_order,guid) VALUES (\'1\',\'2011-06-01 22:12:25\',\'2011-05-09 04:12:25\',\'\',\'\',\'Auto Draft\',\'\',\'inherit\',\'revision\',\'open\',\'open\',\'\',\'100-revision\',\'\',\'\',\'2011-06-01 22:12:25\',\'2011-05-09 04:12:25\',\'%s\',\'0\',\'\')" %bianhao
     sql2="UPDATE wp_posts SET post_author = 1, post_date = \'2011-06-01 22:12:25\', post_date_gmt = \'2011-06-01 22:12:25\', post_content =\'%s\', post_content_filtered = \'\', post_title = \'%s\', post_excerpt = \'\', post_status = \'publish\', post_type = \'post\', comment_status = \'open\', ping_status = \'open\', post_password = \'\', post_name = \'%s\', to_ping = \'\', pinged = \'\', post_modified = \'2011-06-01 22:12:25\', post_modified_gmt = \'2011-05-09 04:12:30\', post_parent = 0, menu_order = 0, guid = \'http://www.moncleronlineshops.com/?p=%s\' WHERE ID = %s" %(Str2,titles,titles,bianhao,bianhao)
     cursor.execute(sql)
     cursor.execute(sql2) #连接数据库并执行这两条语句。
    cursor.close()
     conn.close()  #关闭数据库。
    sys.exit()

上面是程序的代码,采集的是:www.jokeswarehouse.com 的一个笑话网站。通过 python 的 re 模块,也就是正则匹配模块,运行相应的正则表达式,进行过滤出我们所需要的标题和文章内容,再运用 python 的mysqldb 模块,进行连接数据库,利用相应的插入语句,进行插入数据库。

Python 相关文章推荐
python之wxPython菜单使用详解
Sep 28 Python
整理Python最基本的操作字典的方法
Apr 24 Python
从源码解析Python的Flask框架中request对象的用法
Jun 02 Python
详解Python之unittest单元测试代码
Jan 24 Python
深入浅析python 中的匿名函数
May 21 Python
Tensorflow 训练自己的数据集将数据直接导入到内存
Jun 19 Python
Python在for循环中更改list值的方法【推荐】
Aug 17 Python
python3安装crypto出错及解决方法
Jul 30 Python
关于sys.stdout和print的区别详解
Dec 05 Python
基于python tkinter的点名小程序功能的实例代码
Aug 22 Python
python 实现端口扫描工具
Dec 18 Python
python数字图像处理之对比度与亮度调整示例
Jun 28 Python
python结合shell查询google关键词排名的实现代码
Feb 27 #Python
python的else子句使用指南
Feb 27 #Python
Python实现简单多线程任务队列
Feb 27 #Python
如何在Python中编写并发程序
Feb 27 #Python
Python 多线程抓取图片效率对比
Feb 27 #Python
Python 的描述符 descriptor详解
Feb 27 #Python
简析Python的闭包和装饰器
Feb 26 #Python
You might like
Windows中安装Apache2和PHP4权威指南
2006/11/18 PHP
PHP正则表达式入门教程(推荐)
2016/05/18 PHP
php实现的mongoDB单例模式操作类
2018/01/20 PHP
PHP PDOStatement::execute讲解
2019/01/31 PHP
PHP面向对象程序设计重载(overloading)操作详解
2019/06/13 PHP
PHP获取真实IP及IP模拟方法解析
2020/11/24 PHP
分享27款非常棒的jQuery 表单插件
2011/03/28 Javascript
更换select下拉菜单背景样式的实现代码
2011/12/20 Javascript
jquery 动态创建元素的方式介绍及应用
2013/04/21 Javascript
js window.open弹出新的网页窗口
2014/01/16 Javascript
js左右弹性滚动对联广告代码分享
2014/02/19 Javascript
JavaScript中数组的合并以及排序实现示例
2015/10/24 Javascript
Javascript typeof与instanceof的区别
2016/10/18 Javascript
webpack里使用jquery.mCustomScrollbar插件的方法
2018/05/30 jQuery
JS数组求和的常用方法总结【5种方法】
2019/01/14 Javascript
JS模拟浏览器实现全局搜索功能
2019/09/11 Javascript
google广告之另类js调用实现代码
2020/08/22 Javascript
Javascript中window.name属性详解
2020/11/19 Javascript
vue添加自定义右键菜单的完整实例
2020/12/08 Vue.js
[04:42]5分钟带你了解什么是DOTA2(第一期)
2017/02/07 DOTA
Python中3种内建数据结构:列表、元组和字典
2014/11/30 Python
Python实现一个简单的MySQL类
2015/01/07 Python
举例讲解Python中的list列表数据结构用法
2016/03/12 Python
Python编程之序列操作实例详解
2017/07/22 Python
Python中类的初始化特殊方法
2017/12/01 Python
python实现守护进程、守护线程、守护非守护并行
2018/05/05 Python
python 计算概率密度、累计分布、逆函数的例子
2020/02/25 Python
美国眼镜在线零售商:Dualens
2019/12/07 全球购物
Moda Operandi官网:美国奢侈品电商,海淘秀场T台同款
2020/05/26 全球购物
护士自荐信范文
2013/12/15 职场文书
父母对孩子说的话
2014/04/12 职场文书
英语教师求职信
2014/06/16 职场文书
群众路线问题查摆对照检查材料
2014/10/04 职场文书
与死神共舞观后感
2015/06/15 职场文书
Go归并排序算法的实现方法
2022/04/06 Golang
css中:last-child不生效的解决方法
2022/08/05 HTML / CSS