基于python requests selenium爬取excel vba過程解析
目的:基于辦公與互聯(lián)網(wǎng)隔離,自帶的office軟件沒有帶本地幫助工具,因此在寫vba程序時(shí)比較不方便(后來發(fā)現(xiàn)07有自帶,心中吐血,瞎折騰些什么)。所以想到通過爬蟲在官方摘錄下來作為參考。
目標(biāo)網(wǎng)站:https://docs.microsoft.com/zh-cn/office/vba/api/overview/
所使工具:
python3.7,requests、selenium庫
前端方面:使用了jquery、jstree(用于方便的制作無限層級菜單
設(shè)計(jì)思路:
1、分析目標(biāo)頁面,可分出兩部分,左邊時(shí)導(dǎo)航,右邊是內(nèi)容顯示。
2、通過selenium對導(dǎo)航條進(jìn)行深度遍歷,取得導(dǎo)航條所有節(jié)點(diǎn)以及對應(yīng)的鏈接,并以jstree的數(shù)據(jù)格式存儲。
# 導(dǎo)航層級為<ul> <li> <a>... <span>....
3、使用requests遍歷所有鏈接取得相應(yīng)主體頁面。
實(shí)現(xiàn):
## parent 上級節(jié)點(diǎn)# wait_text 上級節(jié)點(diǎn)對應(yīng)的xpath路徑的文本項(xiàng)# level,limit 僅方便測試使用#def GetMenuDick_jstree(parent,level,wait_text,limit=2): if level >= limit: return [] parent.click() l = [] num = 1 new_wati_text = wait_text + ’/following-sibling::ul’ # 只需要等待ul出來就可以了/li[’ + str(ele_num) + ’]’ try: wait.until(EC.presence_of_element_located((By.XPATH,new_wati_text))) # 查詢子節(jié)點(diǎn)所有的 a節(jié)點(diǎn)和span節(jié)點(diǎn)(子菜單) childs = parent.find_elements_by_xpath(’following-sibling::ul/li/span | following-sibling::ul/li/a’) for i in childs: k = {} if i.get_attribute(’role’) == None:k[’text’] = i.text# 如果是子菜單,進(jìn)行深度遍歷k[’children’] = GetMenuDick_jstree(i,level+1,new_wati_text + ’/li[’ + str(num) + ’]/span’,limit) else:# 網(wǎng)頁訪問的Url無Html后綴,需要加上。去除無相關(guān)地址,形成相對路徑。url_text = str(i.get_attribute(’href’)).replace(’https://docs.microsoft.com/zh-cn/office/’, ’’,1) + ’.html’k[’text’] = i.textk[’a_attr’] = {'href':url_text,'target':'showframe'}lhref.append(str(i.get_attribute(’href’))) num = num + 1 l.append(k) parent.click() # 最后收起來 except Exception as e: print(’error message:’,str(e),’error parent:’ ,parent.text,’ new_wati_text:’,new_wati_text,’num:’,str(num)) lerror.append(parent.text) finally: return l
# data菜單,lhref為后續(xù)需要訪問的地址。# 找到第一個(gè)excel節(jié)點(diǎn),從excel開始data = []lhref = []lerror = []k = {}browser.get(start_url)browser.set_page_load_timeout(10) #超時(shí)設(shè)置xpath_text = ’//li[contains(@class,'tree')]/span[text()='Excel'][1]’cl = browser.find_element_by_xpath(xpath_text)k = {’text’:’Excel’}k[’children’] = GetMenuDick_jstree(cl,1,xpath_text,20)data.append(k)# Writing JSON datawith open(r’templetedata.json’, ’w’, encoding=’utf-8’) as f: json.dump(data, f)
進(jìn)行到這里,已經(jīng)擁有了excel vba下所有的菜單信息以及對應(yīng)的url。下來需要得到頁面主體。
實(shí)現(xiàn)思路:
1、遍歷所有url
2、通過url得到相應(yīng)的文件名
## 根據(jù)網(wǎng)頁地址,得到文件名,并創(chuàng)建相應(yīng)文件夾#def create_file(url): t = ’https://docs.microsoft.com/zh-cn/office/’ # 替換掉字眼,然后根據(jù)路徑生成相應(yīng)文件夾 url = url.replace(t,'',1) lname = url.split(’/’) # 先判斷有沒有第一個(gè)文件夾 path = lname[0] if not os.path.isdir(path): os.mkdir(path) for l in lname[1:-1]: path = path + ’’ + str(l) if not os.path.isdir(path): os.mkdir(path) if len(lname) > 1: path = path + ’’ + lname[-1] + ’.html’ return path
3、訪問url得到主體信息儲存。
# requests模式# 循環(huán)遍歷,如果錯(cuò)誤,記錄下來,以后再執(zhí)行had_lhref = []error_lhref = []num = 1for url in lhref: try: had_lhref.append(url) path = create_file(url) resp = requests.get(url,timeout=5,headers = headers) # 設(shè)置訪問超時(shí),以及http頭 resp.encoding = ’utf-8’ html = etree.HTML(resp.text) c = html.xpath(’//main[@id='main']’) # tostring獲取標(biāo)簽所有html內(nèi)容,是字節(jié)類型,要decode為字符串 content = html_head + etree.tostring(c[0], method=’html’).decode(’utf-8’) with open(path,’w’, encoding=’utf-8’) as f: f.write(content) except Exception as e: print(’error message:’,str(e),’error url:’,url) error_lhref.append(url) if num % 10 == 0 : print(’done:’,str(num) + ’/’ + str(len(lhref)),’error num:’ + str(len(error_lhref))) #time.sleep(1) # 睡眠一下,防止被反 num = num + 1
現(xiàn)在,菜單信息與內(nèi)容都有了,需要構(gòu)建自己的主頁,這里使用了jstree;2個(gè)html,index.html,menu.html。
index.html:使用frame頁面框架,相對隔離。
<!DOCTYPE html><html><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'> <title>參考文檔</title> <script src='http://www.aoyou183.cn/bcjs/js/jquery.min.js'> </script></head><frameset rows='93%,7%'> <frameset cols='20%,80%' frameborder='yes' framespacing='1'> <frame src='http://www.aoyou183.cn/bcjs/menu.html' name='menuframe'/> <frame name='showframe' /> </frameset> <frameset frameborder='no' framespacing='1'> <frame src='http://www.aoyou183.cn/bcjs/a.html' /> </frameset></frameset></html>
menu.html:
1、引入了data.json,這樣在可以進(jìn)行離線調(diào)用,使用ajax.get讀取json的話,會提示跨域失敗;
2、jstree會禁止<a>跳轉(zhuǎn)事件,所有需要通過監(jiān)聽'change.tree'事件來進(jìn)行跳轉(zhuǎn)。
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title> <script src='http://www.aoyou183.cn/bcjs/js/jquery.min.js'></script> <link rel='stylesheet' href='http://www.aoyou183.cn/bcjs/themes/default/style.min.css' rel='external nofollow' /> <script src='http://www.aoyou183.cn/bcjs/js/jstree.min.js'></script> <script type='text/javascript' src='http://www.aoyou183.cn/bcjs/data.json'></script></head><body> <div> <form id='s'> <input type='search' /> <button type='submit'>Search</button> </form> <div id='container'> </div> <div id='container'></div> <script> $(function () {$(’#container’).jstree({ 'plugins': ['search', 'changed'], ’core’: { ’data’: data, }}); }); $(’#container’).on('changed.jstree', function (e, data) {//console.log(data.changed.selected.length); // newly selected//console.log(data.changed.deselected); // newly deselectedif (data.changed.selected.length > 0){ // 說明轉(zhuǎn)換了,獲取url var url = data.node.a_attr.href // console.log(url) if (url == '#'){ }else{ parent[data.node.a_attr.target].location.href = url }}else{} }) $('#s').submit(function (e) {e.preventDefault();$('#container').jstree(true).search($('#q').val()); }); </script> </div></body></html>
以上,得到最后的本地版網(wǎng)頁excel vba參考工具。最后,部分office自帶本地版的vba參考工具,有點(diǎn)白干一場。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享2. jsp文件下載功能實(shí)現(xiàn)代碼3. asp.net core項(xiàng)目授權(quán)流程詳解4. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法5. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效6. XMLHTTP資料7. ASP常用日期格式化函數(shù) FormatDate()8. html中的form不提交(排除)某些input 原創(chuàng)9. CSS3中Transition屬性詳解以及示例分享10. ASP基礎(chǔ)入門第八篇(ASP內(nèi)建對象Application和Session)
