python自動打開瀏覽器下載zip并提取內(nèi)容寫入excel
前言
佬們輕噴,里面有些代碼都是現(xiàn)學(xué)現(xiàn)寫的,一些細(xì)節(jié)沒處理好的地方還請指出來~~~
首先貼上效果圖:有些部分我沒有放進來,比如瀏覽器的啟動,但我詳細(xì)聰明的你們那個玩意肯定一學(xué)就會。有些東西我沒放進來

下載
使用到的庫和總體思路
這部分用到time,selenium,urllib,re,requests,os這幾個庫。
代碼
#!/usr/bin/python3
# coding=utf-8
import time
from selenium import webdriver
from urllib.parse import quote,unquote
import re
import requests
import os
# 下面兩個參數(shù)是防止反爬的,別的文章也是這么寫的,但我這里沒用到
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
# 拿到文件對應(yīng)的下載鏈接
def _get_files_url(self):
# 用谷歌瀏覽器打開
driver=webdriver.Chrome()
# 拿到url
driver.get(self.url)
print(driver.title)
time.sleep(5)
# 通過標(biāo)簽id拿到對應(yīng)操作對象
driver.switch_to.frame(0)
driver.find_element_by_id('search_id').send_keys(self.order_number)
# 具體頁面有具體的操作,這里我需要找的button沒有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語法寫的標(biāo)簽很煩。。。我這里先找到目標(biāo)標(biāo)簽的父標(biāo)簽
# 然后通過父標(biāo)簽?zāi)玫侥繕?biāo)標(biāo)簽
dd=driver.find_elements_by_class_name('col-xs-2')
# 我這個父標(biāo)簽下有兩個<a></a>標(biāo)簽,只能要第一個
url_list=[]
for i in dd:
# 因為下載的url正好是第一個,然后這里取得是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):
# 匹配出來的可能有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)建一個保存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:
# 鏈接中附帶了作者和文件名,但是需要解碼,所以先用正則語言提取目標(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庫訪問目標(biāo)頁面,我這里通過_get_files_url方法定位輸入框和超鏈接地址,然后返回超鏈接地址。之后在download_save方法內(nèi)通過request.get拿到文件,然后存在本地,里面的一些存放目錄、文件名處理等細(xì)節(jié)看代碼就可以了。
注意,這只是一個案例,不具備普適性,因為每個頁面的前端編寫方法不盡相同,具體頁面需要具體分析,我這里不貼我的網(wǎng)站是涉及到女朋友的業(yè)務(wù),所以不適合貼。
提取內(nèi)容并填寫
使用到的庫
這部分用到time,xlwt,urllib,re,pickle,os,zipfile,BeautifulSoup這幾個庫。
代碼
#!/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):
'''
這個函數(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:
# 代碼有點長,主要是用于篩選出目標(biāo)文件
target_file=list(filter(lambda x:re.search(r'比對報告.html$',x)!=None,z.namelist()))
# 下面的方法就是比較靈活的
contentb=z.read(target_file[0])
# 這里很頭痛的一點是返回值是二進制的,就算decode了也沒辦法正則匹配
# 所以我想把它存一下再用utf8格式讀取
# 當(dāng)然我也嘗試了decode,但網(wǎng)頁內(nèi)的有些東西還是沒辦法轉(zhuǎn)換,也會導(dǎo)致正則無法匹配
if os.path.exists(self.file_path+'/'+title+'_'+'比對報告.html')==False:
with open(self.file_path+'/'+title+'_'+'比對報告.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)文件解壓出來了,但html文件的讀取比較麻煩,
所以這里用到了BeautifulSoup庫來讀取我想要的信息,
然后把想要的東西存在列表里面返回回來。
:return:
'''
files_list,title_list=self._unzip_files()
repetition_rate=[]
for file in files_list:
# 取出作者和標(biāo)題,這兩個數(shù)據(jù)要寫到excel里面
file=file.split('.')
file=file[0].split('_')
author=file[0]
title=file[1]
# 比對報告已經(jīng)解壓出來了,直接讀取就可以
with open(self.file_path+'/'+title+'_比對報告.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沒有,THIN實線
borders.right = xlwt.Borders.THIN #borders.right=1 表示實線
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()
# 寫一個標(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文件,這就需要先解壓,解壓的庫是zipfile,當(dāng)然這種解壓只是在執(zhí)行的時候解開,不是實際解壓到目錄下面的。解壓出來的文件比較冗雜,所以我用正則匹配了一個最合適(能夠減少編寫工作量)的文件,這部分代碼中的大部分工作都是為了拿到我的目標(biāo)值(其中包括字節(jié)流和字符串的轉(zhuǎn)換工作,我就是失敗了才會選擇保存html文件并重新讀取信息的多余過程),也就是(作者,標(biāo)題,repetition rate),信息寫入excel的過程倒不是很復(fù)雜。我基本上沒有解釋方法是因為這些百度一下或者看官網(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á)到這個效果
到此這篇關(guān)于python自動打開瀏覽器下載zip并提取內(nèi)容寫入excel的文章就介紹到這了,更多相關(guān)python自動瀏覽器下載zip并提取內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
參考文章
- Excel的操作: Python3讀取和寫入excel表格數(shù)據(jù).
- selenium的操作: selenium之 定位以及切換frame(iframe) . Python Selenium庫的使用.
- zip文件的解壓和讀取:Python讀寫zip壓縮文件.
相關(guān)文章
Python 抓取數(shù)據(jù)存儲到Redis中的操作
這篇文章主要介紹了Python 抓取數(shù)據(jù)存儲到Redis中的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
pycharm社區(qū)版安裝django并創(chuàng)建一個簡單項目的全過程
社區(qū)版的pycharm跟專業(yè)版的pycharm應(yīng)用差別還是不太大,下面這篇文章主要給大家介紹了關(guān)于pycharm社區(qū)版安裝django并創(chuàng)建一個簡單項目的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
Python創(chuàng)建exe運行器和截圖工具的示例詳解
本文我們將探討如何使用Python和wxPython創(chuàng)建一個強大而實用的桌面應(yīng)用程序,可以遍歷指定文件夾中的所有EXE文件,感興趣的小伙伴可以了解一下2024-10-10
Python利用pptx操作PPT實現(xiàn)幻燈片的刪除與替換
這篇文章主要為大家詳細(xì)介紹了python如何使用pptx庫實現(xiàn)操作PPTx幻燈片文件刪除并替換圖片,文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下2023-02-02

