python自動(dòng)打開瀏覽器下載zip并提取內(nèi)容寫入excel
前言
佬們輕噴,里面有些代碼都是現(xiàn)學(xué)現(xiàn)寫的,一些細(xì)節(jié)沒(méi)處理好的地方還請(qǐng)指出來(lái)~~~
首先貼上效果圖:有些部分我沒(méi)有放進(jìn)來(lái),比如瀏覽器的啟動(dòng),但我詳細(xì)聰明的你們那個(gè)玩意肯定一學(xué)就會(huì)。有些東西我沒(méi)放進(jìn)來(lái)
下載
使用到的庫(kù)和總體思路
這部分用到time,selenium,urllib,re,requests,os這幾個(gè)庫(kù)。
代碼
#!/usr/bin/python3 # coding=utf-8 import time from selenium import webdriver from urllib.parse import quote,unquote import re import requests import os # 下面兩個(gè)參數(shù)是防止反爬的,別的文章也是這么寫的,但我這里沒(méi)用到 headers = { 'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.5', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36' } params = { 'from': 'search', 'seid': '9698329271136034665' } class Download_file(): def __init__(self,url,order_number,file_path): self.url=url self.order_number=order_number self.file_path=file_path # 拿到文件對(duì)應(yīng)的下載鏈接 def _get_files_url(self): # 用谷歌瀏覽器打開 driver=webdriver.Chrome() # 拿到url driver.get(self.url) print(driver.title) time.sleep(5) # 通過(guò)標(biāo)簽id拿到對(duì)應(yīng)操作對(duì)象 driver.switch_to.frame(0) driver.find_element_by_id('search_id').send_keys(self.order_number) # 具體頁(yè)面有具體的操作,這里我需要找的button沒(méi)有id,他是用ng-click="queryCheckRecordByTid(queryInfo.queryTid)" driver.find_element_by_class_name('btn').click() # driver.find_element_by_id('su').click() time.sleep(3) # AngularJS語(yǔ)法寫的標(biāo)簽很煩。。。我這里先找到目標(biāo)標(biāo)簽的父標(biāo)簽 # 然后通過(guò)父標(biāo)簽?zāi)玫侥繕?biāo)標(biāo)簽 dd=driver.find_elements_by_class_name('col-xs-2') # 我這個(gè)父標(biāo)簽下有兩個(gè)<a></a>標(biāo)簽,只能要第一個(gè) url_list=[] for i in dd: # 因?yàn)橄螺d的url正好是第一個(gè),然后這里取得是element,所以正好取到正確的url a=i.find_element_by_xpath('.//a') # print(a.get_attribute('href')) url_list.append(a.get_attribute('href')) # download_btn[0].click() time.sleep(3) driver.close() return url_list # 下載文件 def download_save(self): # 匹配出來(lái)的可能有None,所以要做一下處理 url_list=self._get_files_url() url_list=list(filter(lambda x:x!=None,url_list)) if len(url_list)==0: return False # 創(chuàng)建一個(gè)保存zip的文件夾 # 更改執(zhí)行路徑的原因是這樣可以靈活的在用戶指定的目錄下創(chuàng)建文件 os.chdir(self.file_path) if os.path.exists(self.file_path+'/'+'Download_Files') == False: os.mkdir('Download_Files') # 更改執(zhí)行路徑 os.chdir(self.file_path + '/'+'Download_Files/') for url in url_list: # 鏈接中附帶了作者和文件名,但是需要解碼,所以先用正則語(yǔ)言提取目標(biāo)串,然后轉(zhuǎn)換成中文 ret = re.search(r'_.*\.zip$',url) file_info=unquote(ret.group()) file_author=file_info.split('_')[1] file_title=file_info.split('_')[2] file_object=requests.get(url) file_name=file_author+'_'+file_title print('正在下載:%s'%file_name) with open(file_name,'wb') as f: f.write(file_object.content) # def auto_fill(self): if __name__ == '__main__': url='http://***' order_id='***' file_path='D:/For discipline/Get_excel' test=Download_file(url,order_id,file_path) test.download_save()
解釋
用selenium庫(kù)訪問(wèn)目標(biāo)頁(yè)面,我這里通過(guò)_get_files_url方法定位輸入框和超鏈接地址,然后返回超鏈接地址。之后在download_save方法內(nèi)通過(guò)request.get拿到文件,然后存在本地,里面的一些存放目錄、文件名處理等細(xì)節(jié)看代碼就可以了。
注意,這只是一個(gè)案例,不具備普適性,因?yàn)槊總€(gè)頁(yè)面的前端編寫方法不盡相同,具體頁(yè)面需要具體分析,我這里不貼我的網(wǎng)站是涉及到女朋友的業(yè)務(wù),所以不適合貼。
提取內(nèi)容并填寫
使用到的庫(kù)
這部分用到time,xlwt,urllib,re,pickle,os,zipfile,BeautifulSoup這幾個(gè)庫(kù)。
代碼
#!/usr/bin/python3 # coding=utf-8 import os import time import xlwt import zipfile import re import pickle from bs4 import BeautifulSoup from Download_files import Download_file class get_excel(): def __init__(self,file_path): self.file_path=file_path # 解壓出目標(biāo)文件 def _unzip_files(self): ''' 這個(gè)函數(shù)具備解壓目標(biāo)文件的功能并且返回需要處理的文件列表 :return: ''' files_list=os.listdir(self.file_path) # 文件名存放在列表中,為了防止處理了別的文件,先用正則匹配一下 files_list=list(filter(lambda x:re.search(r'\.zip$',x)!=None,files_list)) title_list=[] for file in files_list: title=file.split('.')[0].split('_')[1] with zipfile.ZipFile(self.file_path+'/'+file,'r') as z: # 代碼有點(diǎn)長(zhǎng),主要是用于篩選出目標(biāo)文件 target_file=list(filter(lambda x:re.search(r'比對(duì)報(bào)告.html$',x)!=None,z.namelist())) # 下面的方法就是比較靈活的 contentb=z.read(target_file[0]) # 這里很頭痛的一點(diǎn)是返回值是二進(jìn)制的,就算decode了也沒(méi)辦法正則匹配 # 所以我想把它存一下再用utf8格式讀取 # 當(dāng)然我也嘗試了decode,但網(wǎng)頁(yè)內(nèi)的有些東西還是沒(méi)辦法轉(zhuǎn)換,也會(huì)導(dǎo)致正則無(wú)法匹配 if os.path.exists(self.file_path+'/'+title+'_'+'比對(duì)報(bào)告.html')==False: with open(self.file_path+'/'+title+'_'+'比對(duì)報(bào)告.html','wb') as fb: pickle.dump(contentb,fb) # with open(self.file_path+'/'+target_file[0],'r',encoding='utf-8') as fa: # contenta=fa.read() # print(contenta) # sentence=str(re.search(r'<b [^"]*red tahoma.*</b>$',contenta)) # value=re.search(r'\d.*%', sentence) # info=[author,title,value] # repetition_rate.append(info) title_list.append(target_file[0]) return files_list,title_list # 讀取html文件內(nèi)容 def read_html(self): ''' 之前的函數(shù)已經(jīng)把目標(biāo)文件解壓出來(lái)了,但html文件的讀取比較麻煩, 所以這里用到了BeautifulSoup庫(kù)來(lái)讀取我想要的信息, 然后把想要的東西存在列表里面返回回來(lái)。 :return: ''' files_list,title_list=self._unzip_files() repetition_rate=[] for file in files_list: # 取出作者和標(biāo)題,這兩個(gè)數(shù)據(jù)要寫到excel里面 file=file.split('.') file=file[0].split('_') author=file[0] title=file[1] # 比對(duì)報(bào)告已經(jīng)解壓出來(lái)了,直接讀取就可以 with open(self.file_path+'/'+title+'_比對(duì)報(bào)告.html','rb') as f: # 下面是BeautifulSoup的用法,看不懂的話可以去官網(wǎng) content=f.read() content=BeautifulSoup(content,"html.parser") # print(type(content)) # 網(wǎng)上搜了很多,終于可以找到我想要的重復(fù)率了 value=content.find('b',{"class":"red tahoma"}).string repetition_rate.append([author,title,value]) return repetition_rate def write_excel(self): ''' 生成xls表格 :return: ''' workbook=xlwt.Workbook(encoding='utf-8') booksheet=workbook.add_sheet('Sheet1') # 設(shè)置邊框 borders = xlwt.Borders() # Create Borders borders.left = xlwt.Borders.THIN #DASHED虛線,NO_LINE沒(méi)有,THIN實(shí)線 borders.right = xlwt.Borders.THIN #borders.right=1 表示實(shí)線 borders.top = xlwt.Borders.THIN borders.bottom = xlwt.Borders.THIN borders.left_colour=0x40 borders.right_colour = 0x40 borders.top_colour = 0x40 borders.bottom_colour = 0x40 style1=xlwt.XFStyle() style1.borders=borders # 設(shè)置背景顏色,這些操作搞得很像js和css pattern = xlwt.Pattern() pattern.pattern = xlwt.Pattern.SOLID_PATTERN pattern.pattern_fore_colour = 44 style = xlwt.XFStyle() # Create the Pattern style.pattern = pattern repetition_rate=self.read_html() # 寫一個(gè)標(biāo)題 booksheet.write(0,0,'作者',style) booksheet.write(0,1,'標(biāo)題',style) booksheet.write(0,2,'重復(fù)率',style) for item in repetition_rate: booksheet.write(repetition_rate.index(item)+1,0,item[0],style1) booksheet.write(repetition_rate.index(item)+1,1,item[1],style1) booksheet.write(repetition_rate.index(item)+1,2,item[2],style1) s='重復(fù)率.xls' workbook.save(self.file_path+'/'+s) if __name__ == '__main__': # 判斷一下Download_files文件夾 file_path='D:/For discipline/Get_excel' url='http://***' order_number='***' if os.path.exists('./Download_Files')==False: get_file=Download_file(url,order_number,file_path) get_file.download_save() os.chdir(file_path+'/Download_Files') test=get_excel('D:/For discipline/Get_excel/Download_Files') test.write_excel()
解釋
由于我下載的zip文件,這就需要先解壓,解壓的庫(kù)是zipfile,當(dāng)然這種解壓只是在執(zhí)行的時(shí)候解開,不是實(shí)際解壓到目錄下面的。解壓出來(lái)的文件比較冗雜,所以我用正則匹配了一個(gè)最合適(能夠減少編寫工作量)的文件,這部分代碼中的大部分工作都是為了拿到我的目標(biāo)值(其中包括字節(jié)流和字符串的轉(zhuǎn)換工作,我就是失敗了才會(huì)選擇保存html文件并重新讀取信息的多余過(guò)程),也就是(作者,標(biāo)題,repetition rate),信息寫入excel的過(guò)程倒不是很復(fù)雜。我基本上沒(méi)有解釋方法是因?yàn)檫@些百度一下或者看官網(wǎng)就行了,主要還是闡述一下我的編寫思路
附:Python使用beautifulSoup獲取標(biāo)簽內(nèi)數(shù)據(jù)
from bs4 import BeautifulSoup for k in soup.find_all('a'): print(k) print(k['class'])#查a標(biāo)簽的class屬性 print(k['id'])#查a標(biāo)簽的id值 print(k['href'])#查a標(biāo)簽的href值 print(k.string)#查a標(biāo)簽的string #tag.get('calss'),也可以達(dá)到這個(gè)效果
到此這篇關(guān)于python自動(dòng)打開瀏覽器下載zip并提取內(nèi)容寫入excel的文章就介紹到這了,更多相關(guān)python自動(dòng)瀏覽器下載zip并提取內(nèi)容內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
參考文章
- Excel的操作: Python3讀取和寫入excel表格數(shù)據(jù).
- selenium的操作: selenium之 定位以及切換frame(iframe) . Python Selenium庫(kù)的使用.
- zip文件的解壓和讀?。?a target="_blank" href="http://www.dbjr.com.cn/article/146469.htm">Python讀寫zip壓縮文件.
相關(guān)文章
Python 抓取數(shù)據(jù)存儲(chǔ)到Redis中的操作
這篇文章主要介紹了Python 抓取數(shù)據(jù)存儲(chǔ)到Redis中的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07pycharm社區(qū)版安裝django并創(chuàng)建一個(gè)簡(jiǎn)單項(xiàng)目的全過(guò)程
社區(qū)版的pycharm跟專業(yè)版的pycharm應(yīng)用差別還是不太大,下面這篇文章主要給大家介紹了關(guān)于pycharm社區(qū)版安裝django并創(chuàng)建一個(gè)簡(jiǎn)單項(xiàng)目的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05Python創(chuàng)建exe運(yùn)行器和截圖工具的示例詳解
本文我們將探討如何使用Python和wxPython創(chuàng)建一個(gè)強(qiáng)大而實(shí)用的桌面應(yīng)用程序,可以遍歷指定文件夾中的所有EXE文件,感興趣的小伙伴可以了解一下2024-10-10Python執(zhí)行ping操作的簡(jiǎn)單方法
本文主要介紹了Python執(zhí)行ping操作的簡(jiǎn)單方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02使用PyTorch訓(xùn)練一個(gè)圖像分類器實(shí)例
今天小編就為大家分享一篇使用PyTorch訓(xùn)練一個(gè)圖像分類器實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01Python利用pptx操作PPT實(shí)現(xiàn)幻燈片的刪除與替換
這篇文章主要為大家詳細(xì)介紹了python如何使用pptx庫(kù)實(shí)現(xiàn)操作PPTx幻燈片文件刪除并替換圖片,文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下2023-02-02