最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于python requests selenium爬取excel vba過程解析

 更新時間:2020年08月12日 09:44:55   作者:forxtz  
這篇文章主要介紹了基于python requests selenium爬取excel vba過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

目的:基于辦公與互聯(lián)網(wǎng)隔離,自帶的office軟件沒有帶本地幫助工具,因此在寫vba程序時比較不方便(后來發(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è)計思路:

1、分析目標(biāo)頁面,可分出兩部分,左邊時導(dǎo)航,右邊是內(nèi)容顯示。

2、通過selenium對導(dǎo)航條進(jìn)行深度遍歷,取得導(dǎo)航條所有節(jié)點以及對應(yīng)的鏈接,并以jstree的數(shù)據(jù)格式存儲。

# 導(dǎo)航層級為
<ul>
  <li>
    <a>...
    <span>....

3、使用requests遍歷所有鏈接取得相應(yīng)主體頁面。

實現(xiàn):

#
# parent 上級節(jié)點
# wait_text 上級節(jié)點對應(yīng)的xpath路徑的文本項
# 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é)點所有的 a節(jié)點和span節(jié)點(子菜單)
    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.text
        k['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ù)需要訪問的地址。
# 找到第一個excel節(jié)點,從excel開始
data = []
lhref = []
lerror = []
k = {}
browser.get(start_url)
browser.set_page_load_timeout(10)  #超時設(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 data
with open(r'templete\data.json', 'w', encoding='utf-8') as f:
  json.dump(data, f)

進(jìn)行到這里,已經(jīng)擁有了excel vba下所有的菜單信息以及對應(yīng)的url。下來需要得到頁面主體。

實現(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('/')
  # 先判斷有沒有第一個文件夾
  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)遍歷,如果錯誤,記錄下來,以后再執(zhí)行
had_lhref = []
error_lhref = []
num = 1
for url in lhref:
  try:
    had_lhref.append(url)
    path = create_file(url)
    resp = requests.get(url,timeout=5,headers = headers) # 設(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個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="js/jquery.min.js"> </script>
</head>
<frameset rows="93%,7%">
  <frameset cols="20%,80%" frameborder="yes" framespacing="1">
    <frame src="menu.html" name="menuframe"/>
    <frame id="showframe" name="showframe" />
  </frameset>
  <frameset frameborder="no" framespacing="1">
    <frame src="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="js/jquery.min.js"></script>
  <link rel="stylesheet" href="themes/default/style.min.css" rel="external nofollow" />
  <script src="js/jstree.min.js"></script>
  <script type="text/javascript" src="data.json"></script>
</head>

<body>
  <div>

    <form id="s">
      <input type="search" id="q" />
      <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 deselected
        if (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參考工具,有點白干一場。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python如何將aac轉(zhuǎn)為mp3,保持原有目錄結(jié)構(gòu)

    python如何將aac轉(zhuǎn)為mp3,保持原有目錄結(jié)構(gòu)

    使用Python腳本實現(xiàn)AAC格式轉(zhuǎn)MP3格式的方法介紹,需要用戶輸入AAC文件所在目錄路徑和MP3輸出目錄路徑,通過調(diào)用FFmpeg工具實現(xiàn)格式轉(zhuǎn)換,該腳本簡單易懂,適合需要批量處理音頻文件的用戶,使用前需確保已安裝FFmpeg環(huán)境
    2024-11-11
  • 使用Python批量壓縮tif文件操作步驟

    使用Python批量壓縮tif文件操作步驟

    Tif文件是柵格數(shù)據(jù)最常用的一種格式。圖像數(shù)據(jù)區(qū)以位圖的方式進(jìn)行數(shù)據(jù)的表示。因此Tif文件可以進(jìn)行壓縮,常用的壓縮方式有LZW、RAW、RLE、CCITT等
    2021-09-09
  • Python實現(xiàn)Excel自動分組合并單元格

    Python實現(xiàn)Excel自動分組合并單元格

    這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)Excel自動分組合并單元格,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-02-02
  • 利用pandas進(jìn)行數(shù)據(jù)清洗的7種方式

    利用pandas進(jìn)行數(shù)據(jù)清洗的7種方式

    采集到原始的數(shù)據(jù)中會存在一些噪點數(shù)據(jù),噪點數(shù)據(jù)是對分析無意義或者對分析起到偏執(zhí)作用的數(shù)據(jù),所以這篇文章給大家介紹了利用pandas進(jìn)行數(shù)據(jù)清洗的7種方式,需要的朋友可以參考下
    2024-03-03
  • 使用Matplotlib將圖片保存為.tiff格式

    使用Matplotlib將圖片保存為.tiff格式

    這篇文章主要介紹了使用Matplotlib將圖片保存為.tiff格式問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 一文搞懂Python Sklearn庫使用

    一文搞懂Python Sklearn庫使用

    Python sklearn庫是一個豐富的機(jī)器學(xué)習(xí),本文通過實例代碼給大家介紹了Python Sklearn庫使用方法,需要的朋友可以參考下
    2021-08-08
  • Python在報表自動化的優(yōu)勢及實現(xiàn)流程

    Python在報表自動化的優(yōu)勢及實現(xiàn)流程

    本文利用Python實現(xiàn)報表自動化,通過介紹環(huán)境設(shè)置、數(shù)據(jù)收集和準(zhǔn)備、報表生成以及自動化流程,展示Python的靈活性和豐富的生態(tài)系統(tǒng)在報表自動化中的卓越表現(xiàn),從設(shè)置虛擬環(huán)境到使用Pandas和Matplotlib處理數(shù)據(jù),到借助APScheduler實現(xiàn)定期自動化,每個步驟都得到詳盡闡述
    2023-12-12
  • 如何通過命令行進(jìn)入python

    如何通過命令行進(jìn)入python

    在本篇文章中小編給各位分享的是一篇關(guān)于命令行進(jìn)入python的方法,有需要的朋友們學(xué)習(xí)一下。
    2020-07-07
  • Python pandas庫中的isnull()詳解

    Python pandas庫中的isnull()詳解

    今天小編就為大家分享一篇Python pandas庫中的isnull()詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • pandas創(chuàng)建series的三種方法小結(jié)

    pandas創(chuàng)建series的三種方法小結(jié)

    這篇文章主要介紹了pandas創(chuàng)建series的三種方法小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05

最新評論

蓝山县| 颍上县| 玛沁县| 莆田市| 石泉县| 梅河口市| 九龙县| 若羌县| 化隆| 建阳市| 盐津县| 蒙自县| 封开县| 始兴县| 福建省| 昆山市| 佛教| 通州区| 墨竹工卡县| 杭锦旗| 伊宁市| 重庆市| 邮箱| 阿拉尔市| 苗栗市| 高青县| 博客| 莱西市| 尖扎县| 定西市| 九龙坡区| 章丘市| 开江县| 卓资县| 芒康县| 洞头县| 金沙县| 彩票| 平舆县| 沾化县| 车致|