百度貼吧爬蟲

來源:互聯網
上載者:User
2011-09-28 一 代碼
#coding:gb2312import urllib2,urllib,re,osimport sqlite3,cookielib,time'''    百度爬蟲類    @author:FC_LAMP'''class SpiderBaiDu:   #變數    sqlit = None    cur   = None    baseurl = 'http://hi.baidu.com'    total  = 0    #處理單引號    def qutoSin(self,string):        return string.replace("'","")     #登陸百度空間    '''      user 為使用者名稱      pwd  為password    '''    def LoginBaiDu(self,user,pwd):                #設定        cookie = cookielib.CookieJar()        cookieProc = urllib2.HTTPCookieProcessor(cookie)        opener = urllib2.build_opener(cookieProc)        urllib2.install_opener(opener)        #請求        header = {'User-Agent':'Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2'}        post = {            'username':user,            'password':pwd,            'tpl':'mn',            'u':'http://www.baidu.com/',            'psp_tt':0,            'mem_pass':'on'            }        post = urllib.urlencode(post)                req = urllib2.Request(            url='https://passport.baidu.com/?login',            data=post,            headers = header            )        res = urllib2.urlopen(req).read(500)                if 'passCookie' in res:            flag = True        else:            flag = 'Login Fail:%s'%user                    return flag    #建立資料庫    '''        dbFile 為資料庫檔案    '''    def created_db(self,dbFile):        #        dbFile = dbFile.replace("\\","/")        self.sqlit = sqlite3.connect(dbFile)        self.cur = self.sqlit.cursor()        sql = """            CREATE TABLE IF NOT EXISTS `article`            (                 a_id char(24) PRIMARY KEY,                 title varchar(255),                 created_time datetime,                 category varchar(255),                 orgurl varchar(255),                 content text            )            """        self.cur.execute(sql)        self.sqlit.commit()        #注更多關於python資料庫的操作:http://hi.baidu.com/fc_lamp/blog/item/3d48778a1f93d06a9e2fb4c3.html                    #分析頁面    '''        url 為要分析頁面的起始URL        debug 當為True時,將會列印出調試資訊    '''    def parse_html(self,url,debug=False):                while True:            c = urllib2.urlopen(url).read()                        #標題,時間            #正則編義(注意後面的修飾)            p = re.compile(                    r'<div.*?id="?m_blog"?.*?<div.*?class="?tit"?>(.*?)<\/div>.*?<div.*?class="?date"?>(.*?)<\/div>',                    re.S|re.I                    )            m = p.search(c)            if m==None:                break            title = m.group(1).strip()            date  = m.group(2).strip()            date  = date.split(' ')            date  = date[0]+' '+date[1]                        #內容            s = re.compile(                    r'<div\s*?id="?blog_text"?\s*?class="?cnt"?\s*?>(.*?)<\/div>',                    re.S|re.I                )            m = s.search(c)                     content = m.group(1).strip()            #類別            s = re.compile(                    '類別:(.*?)<\/a>',                    re.S|re.I|re.U                )            m = s.search(c)            category = m.group(1).strip()            #源連結            orgurl = re.compile(                    'myref.*?=.*?encodeURIComponent\("(.*?)"\)',                    re.S|re.I|re.U                )            orgurl = orgurl.search(c)            orgurl = orgurl.group(1).strip()            aid = os.path.split(orgurl)            aid = aid[1].split('%2E')[0]                        #注意正則最後一個)手動加轉義符\,原因參看:http://hi.baidu.com/fc_lamp/blog/item/1e8bab1f258c58e31bd5769e.html            #通過元組            sql = 'insert into `article`(a_id,title,created_time,category,orgurl,content)'            values = "values('%s','%s','%s','%s','%s','%s')"%(aid,self.qutoSin(title),date,self.qutoSin(category),orgurl,self.qutoSin(content))            sql+=values                        #插入資料庫            self.cur.execute(sql)            self.sqlit.commit()            self.total +=1            #下一篇            nexturl = re.compile(                    'var\s*?post\s*?=\s*?\[true,\'.*?\',\'.*?\',(.*?)]',#注意這裡最後一個]沒手動加轉義符\                     re.S|re.I|re.U                )            nexturl = nexturl.search(c)            if nexturl==None:                break            nexturl = self.qutoSin(nexturl.group(1).strip()).replace("\\",'')            nexturl = self.baseurl+nexturl            url = nexturl            #輸出調試資訊            if debug:                print(title)                print(date)                print('nextUrl:'+url+'\n')           #睡上一秒           time.sleep(1)   二 例子我們可以單獨把SpiderBaiDu()類放一個模組,在使用時就很方便,下面這個例子是一個不登陸爬取的例子。#coding:gb2312import spider,time#匯入模組if __name__ == '__main__':    st = time.time()    print('解析中......')    spider = spider.SpiderBaiDu()   #若要登陸加上:spider.LoginBaiDu(xxxx,xxxxx)    spider.created_db(r"D:\test2.db3")    url = 'http://hi.baidu.com/fc_lamp/xxxxxxx.html'#起始URL    try:        spider.parse_html(url,debug=True)    except Exception as e:        print('Error:',e)    et = time.time()    c = et - st    print('程式運行耗時:%0.2fs'%c)    print('總共爬取了 %d 篇文章'%spider.total) 三 結果1過程:2 資料檔案:   #參考資料#關於python裡正則使用 參看 1http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html#                        2http://hi.baidu.com/fc_lamp/blog/item/1e8bab1f258c58e31bd5769e.html#關於資料庫操作,參看http://hi.baidu.com/fc_lamp/blog/item/3d48778a1f93d06a9e2fb4c3.html#關於cookie登陸問題,參看http://hi.baidu.com/fc_lamp/blog/item/2d947745fc31cf9fb2b7dc0a.html#關於 python 異常處理,參看http://hi.baidu.com/fc_lamp/blog/item/8a07f31e3e5c56dca7866992.html#關於保留小數位問題:請參看http://hi.baidu.com/fc_lamp/blog/item/09555100745c3eda267fb554.html#Python 登陸163郵箱,並擷取通訊錄http://hi.baidu.com/fc_lamp/blog/item/2466d1096fcc532de8248839.html ps :爬蟲慎用~~

原文地址,

http://hi.baidu.com/fc_lamp/blog/item/03489c919a836091a977a48c.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.