[Python爬蟲] 之十五:Selenium +phantomjs根據微信公衆號抓取微信文章

  藉助搜索微信搜索引擎進行抓取html

  抓取過程python

  一、首先在搜狗的微信搜索頁面測試一下,這樣可以讓咱們的思路更加清晰web

  

    在搜索引擎上使用微信公衆號英文名進行「搜公衆號」操做(由於公衆號英文名是公衆號惟一的,而中文名可能會有重複,同時公衆號名字必定要徹底正確,否則可能搜到不少東西,這樣咱們能夠減小數據的篩選工做,json

    只要找到這個惟一英文名對應的那條數據便可),即發送請求到'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&_sug_=n&_sug_type_= ' %  'Python',並從頁面中解析出搜索結果公衆號對應的主頁跳轉連接。微信

    

  在抓取過程當中用到了pyquery 也能夠用xpathsession

  

  文件保存:app

  

 

  完整代碼以下:異步

  

# coding: utf-8# 這三行代碼是防止在python2上面編碼錯誤的,在python3上面不要要這樣設置import sysreload(sys)sys.setdefaultencoding('utf-8')from urllib import quotefrom pyquery import PyQuery as pqfrom selenium import webdriverfrom pyExcelerator import *  # 導入excel相關包import requestsimport timeimport reimport jsonimport osclass wx_spider:    def __init__(self,Wechat_PublicID):        '''        構造函數,藉助搜狗微信搜索引擎,根據微信公衆號獲取微信公衆號對應的文章的,發佈時間、文章標題, 文章連接, 文章簡介等信息        :param Wechat_PublicID: 微信公衆號        '''        self.Wechat_PublicID = Wechat_PublicID        #搜狗引擎連接url        self.sogou_search_url = 'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&s_from=input&_sug_=n&_sug_type_=' % quote(Wechat_PublicID)        # 爬蟲假裝頭部設置        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}        # 超時時長        self.timeout = 5        # 爬蟲模擬在一個request.session中完成        self.session = requests.Session()        # excel 第一行數據        self.excel_headData = [u'發佈時間', u'文章標題', u'文章連接', u'文章簡介']        # 定義excel操做句柄        self.excle_Workbook = Workbook()    def log(self, msg):        '''        日誌函數        :param msg: 日誌信息        :return:        '''        print u'%s: %s' % (time.strftime('%Y-%m-%d %H-%M-%S'), msg)    def run(self):        #Step 0 :  建立公衆號命名的文件夾        if not os.path.exists(self.Wechat_PublicID):            os.makedirs(self.Wechat_PublicID)        # 第一步 :GET請求到搜狗微信引擎,以微信公衆號英文名稱做爲查詢關鍵字        self.log(u'開始獲取,微信公衆號英文名爲:%s' % self.Wechat_PublicID)        self.log(u'開始調用sougou搜索引擎')        self.log(u'搜索地址爲:%s' % self.sogou_search_url)        sougou_search_html = self.session.get(self.sogou_search_url, headers=self.headers, timeout=self.timeout).content        # 第二步:從搜索結果頁中解析出公衆號主頁連接        doc = pq(sougou_search_html)        # 經過pyquery的方式處理網頁內容,相似用beautifulsoup,可是pyquery和jQuery的方法相似,找到公衆號主頁地址        wx_url = doc('div[class=txt-box]')('p[class=tit]')('a').attr('href')        self.log(u'獲取wx_url成功,%s' % wx_url)        # 第三步:Selenium+PhantomJs獲取js異步加載渲染後的html        self.log(u'開始調用selenium渲染html')        browser = webdriver.PhantomJS()        browser.get(wx_url)        time.sleep(3)        # 執行js獲得整個頁面內容        selenium_html = browser.execute_script("return document.documentElement.outerHTML")        browser.close()        # 第四步: 檢測目標網站是否進行了封鎖        ' 有時候對方會封鎖ip,這裏作一下判斷,檢測html中是否包含id=verify_change的標籤,有的話,表明被重定向了,提醒過一陣子重試 '        if pq(selenium_html)('#verify_change').text() != '':            self.log(u'爬蟲被目標網站封鎖,請稍後再試')        else:            # 第五步: 使用PyQuery,從第三步獲取的html中解析出公衆號文章列表的數據            self.log(u'調用selenium渲染html完成,開始解析公衆號文章')            doc = pq(selenium_html)            articles_list = doc('div[class="weui_media_box appmsg"]')            articlesLength = len(articles_list)            self.log(u'抓取到微信文章%d篇' % articlesLength)            # Step 6: 把微信文章數據封裝成字典的list            self.log(u'開始整合微信文章數據爲字典')            # 遍歷找到的文章,解析裏面的內容            if articles_list:                index = 0                # 以當前時間爲名字建表                excel_sheet_name = time.strftime('%Y-%m-%d')                excel_content = self.excle_Workbook.add_sheet(excel_sheet_name)                colindex = 0                columnsLength = len(self.excel_headData)                for data in self.excel_headData:                    excel_content.write(0, colindex, data)                    colindex += 1                for article in articles_list.items():                    self.log(' ' )                    self.log(u'開始整合(%d/%d)' % (index, articlesLength))                    index += 1                    # 處理單個文章                    # 獲取標題                    title = article('h4[class="weui_media_title"]').text().strip()                    self.log(u'標題是: %s' % title)                    # 獲取標題對應的地址                    url = 'http://mp.weixin.qq.com' + article('h4[class="weui_media_title"]').attr('hrefs')                    self.log(u'地址爲: %s' % url)                    # 獲取概要內容                    # summary = article('.weui_media_desc').text()                    summary = article('p[class="weui_media_desc"]').text()                    self.log(u'文章簡述: %s' % summary)                    # 獲取文章發表時間                    # date = article('.weui_media_extra_info').text().strip()                    date = article('p[class="weui_media_extra_info"]').text().strip()                    self.log(u'發表時間爲: %s' % date)                    # # 獲取封面圖片                    # pic = article('.weui_media_hd').attr('style')                    #                    # p = re.compile(r'background-image:url(.+)')                    # rs = p.findall(pic)                    # if len(rs) > 0:                    #     p = rs[0].replace('(', '')                    #     p = p.replace(')', '')                    #     self.log(u'封面圖片是:%s ' % p)                    tempContent = [date, title, url, summary]                    for j in range(columnsLength):                        excel_content.write(index, j, tempContent[j])                    self.excle_Workbook.save(self.Wechat_PublicID + '/' + self.Wechat_PublicID + '.xlsx')            self.log(u'保存完成,程序結束')if __name__ == '__main__':    wx_spider("python6359").run()
相關文章
相關標籤/搜索