在學習python的過程中,經過不斷的嘗試及努力,終于完成了第一個像樣的python程式,雖然還有很多需要優化的地方,但是目前基本上實作了我所要求的功能,先貼一下程式代碼:

具體代碼如下
#! /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 子產品,進行連接配接資料庫,利用相應的插入語句,進行插入資料庫。