您好,登錄后才能下訂單哦!
這篇文章主要介紹Python中selenium爬取微信公眾號(hào)文章的方法,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
需求:
想閱讀微信公眾號(hào)歷史文章,但是每次找回看得地方不方便。
思路:
1、使用selenium打開(kāi)微信公眾號(hào)歷史文章,并滾動(dòng)刷新到最底部,獲取到所有歷史文章urls。
2、對(duì)urls進(jìn)行遍歷訪問(wèn),并進(jìn)行下載到本地。
實(shí)現(xiàn)
1、打開(kāi)微信客戶端,點(diǎn)擊某個(gè)微信公眾號(hào)->進(jìn)入公眾號(hào)->打開(kāi)歷史文章鏈接(使用瀏覽器打開(kāi)),并通過(guò)開(kāi)發(fā)者工具獲取到cookies,保存為excel。
2、啟動(dòng)webdriver,并添加相應(yīng)cookies。
browser = webdriver.Chrome() wait = WebDriverWait(browser,10) # 隨便訪問(wèn)一個(gè)地址,然后才能設(shè)置cookies browser.get('https://httpbin.org/get') # 添加cookies,df為保存的excel cookies for i in range(len(df)): cookie_dict = { "domain": df.loc[i,'DomaiN'], 'name': df.loc[i,'Name'], 'value': str(df.loc[i,'Value']), "expires": df.loc[i,"Expires/Max-Age"], 'path': '/',} browser.add_cookie(cookie_dict) browser.get(weixin_url)
3、控制瀏覽器下移動(dòng)
觀察page_source,可以發(fā)現(xiàn),文章到最底部的判斷是。
<div class="loadmore with_line" id="js_nomore"> <div class="tips_wrp"> <span class="tips js_no_more_msg" >已無(wú)更多</span> <span class="tips js_need_add_contact" >關(guān)注公眾帳號(hào),接收更多消息</span> </div> </div>
使用driver控制JS。
%%time # 通過(guò)判斷已無(wú)更多的style,來(lái)判斷是否到最底部,最終執(zhí)行到最底部 no_more_msg_style = 'display: none;' while True: wait.until(EC.presence_of_element_located((By.XPATH,'//span[@class="tips js_no_more_msg" and text()="已無(wú)更多"]'))) no_more= browser.find_element_by_xpath('//span[@class="tips js_no_more_msg" and text()="已無(wú)更多"]') now_style = no_more.get_attribute('style') if str(now_style).find(no_more_msg_style) == -1: # 說(shuō)明已經(jīng)加載完了 break else: # 停頓一會(huì),等待瀏覽器加載 time.sleep(5) # 通過(guò)JS,執(zhí)行到最底部 browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')
4、關(guān)鍵信息獲取。
根據(jù)html,分析得出文章url處在<div msgid="1000000026">中。
<div class="weui_msg_card js_card" msgid="1000000026"> <div class="weui_msg_card_hd">2017年1月13日</div> <div class="weui_msg_card_bd"> <!-- 圖文 --> <!-- 普通圖文 --> <div id="WXAPPMSG1000000026" class="weui_media_box appmsg js_appmsg" hrefs="http://mp.weixin.qq.com/s?__biz=MzI5MDQ4NzU5MA==&mid=2247483748&idx=1&sn=e804e638484794181a27c094f81be8e1&chksm=ec1e6d2ddb69e43bd3e1f554c2d0cedb37f099252f122cee1ac5052b589b56f428b2c304de8e&scene=38#wechat_redirect" data-t="0"> <span class="weui_media_hd js_media" data-s="640" hrefs="http://mp.weixin.qq.com/s?__biz=MzI5MDQ4NzU5MA==&mid=2247483748&idx=1&sn=e804e638484794181a27c094f81be8e1&chksm=ec1e6d2ddb69e43bd3e1f554c2d0cedb37f099252f122cee1ac5052b589b56f428b2c304de8e&scene=38#wechat_redirect" data-type="APPMSG"> </span> <div class="weui_media_bd js_media" data-type="APPMSG"> <h5 class="weui_media_title" hrefs="http://mp.weixin.qq.com/s?__biz=MzI5MDQ4NzU5MA==&mid=2247483748&idx=1&sn=e804e638484794181a27c094f81be8e1&chksm=ec1e6d2ddb69e43bd3e1f554c2d0cedb37f099252f122cee1ac5052b589b56f428b2c304de8e&scene=38#wechat_redirect"> 承認(rèn)自己是難民有什么錯(cuò) </h5> <p class="weui_media_desc">枷鎖已經(jīng)足夠沉重,謝絕道德綁架</p> <p class="weui_media_extra_info">2017年1月13日</p> </div> </div> </div> </div>
文章類型主要分為,
<div class="weui_media_bd js_media" data-type="APPMSG">
<div class="weui_media_bd js_media" data-type="TEXT">
有無(wú)原創(chuàng)進(jìn)行劃分。
最終實(shí)現(xiàn):
%%time result = [] errlist = [] # 先得到其中一個(gè) el_divs = browser.find_elements_by_xpath('//div[@class="weui_msg_card_list"]/div[@class="weui_msg_card js_card"]') i = 0 for div in el_divs: date = title = url = yuanchuang = '' try: date = div.find_element_by_xpath('.//div[@class="weui_msg_card_hd"]').get_attribute('innerHTML') el_content = div.find_element_by_xpath('.//div[@class="weui_media_bd js_media"]') if el_content.get_attribute('data-type') == 'APPMSG': el = el_content.find_element_by_xpath('./h5[@class="weui_media_title"]') title = el.text url = el.get_attribute('hrefs') xb = el_content.find_element_by_xpath('./p[@class="weui_media_extra_info"]').text yuanchuang = '原創(chuàng)' if xb.find('原創(chuàng)') != -1 else '' elif el_content.get_attribute('data-type') == 'TEXT': title = '隨文' url = el_content.find_element_by_xpath('./div').text yuanchuang = '原創(chuàng)' else: # 其他未能識(shí)別的類型 errlist.append([i,div.get_attribute('innerHTML')]) except NoSuchElementException: errlist.append([i,div.get_attribute('innerHTML')]) print(str(i),':',date,title,url,yuanchuang) result.append([date,title,yuanchuang,url]) i = i + 1
5、將得到url保存到excel
dfout = pd.DataFrame(result, columns=['日期', '標(biāo)題', '原創(chuàng)', '地址'])
with pd.ExcelWriter(savename) as writer:
dfout.to_excel(writer,index=False,sheet_name = 'Sheet1')
最終保存形式
6、在遍歷最后的鏈接地址,逐個(gè)requets保存,即可得到。組建成菜單形式的文章,可參考
記一次 excel vba 參考手冊(cè)爬蟲實(shí)戰(zhàn),不必要的一次爬蟲。:htthttps://www.jb51.net/article/193107.htm
遇到的坑:
1、find_element_by_xpath 需要配上 NoSuchElementException 使用,否則遇到未找到的節(jié)點(diǎn)就會(huì)出錯(cuò),最初find_elements_by_xpath 來(lái)防止找不到相關(guān)節(jié)點(diǎn),結(jié)果發(fā)現(xiàn),執(zhí)行速度異常的慢,需要查找原因。
2、cookies使用的時(shí)候是人為獲取,如果太長(zhǎng)時(shí)間不用,需要重新獲取??梢钥紤]結(jié)合pyautogui來(lái)控制weixin客戶端來(lái)進(jìn)行獲取。?
3、構(gòu)建的時(shí)候,最后分布試行,最初的文章類型沒(méi)有做好判斷,結(jié)果執(zhí)行時(shí)間很久。做好異常捕獲,再逐步分析錯(cuò)誤的節(jié)點(diǎn)問(wèn)題。
以上是Python中selenium爬取微信公眾號(hào)文章的方法的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。