1. 程式人生 > 其它 >python自動開啟瀏覽器下載zip,並且提取內容寫入excel

python自動開啟瀏覽器下載zip,並且提取內容寫入excel

佬們輕噴,裡面有些程式碼都是現學現寫的,一些細節沒處理好的地方還請指出來~~~
首先貼上效果圖:有些部分我沒有放進來,比如瀏覽器的啟動,但我相信聰明的你們那個玩意肯定一學就會。有些東西我沒放進來

程式碼思路
下載
使用到的庫
程式碼
解釋
提取內容並填寫
使用到的庫
程式碼
解釋
後續發現的問題
參考文章
下載
使用到的庫
這部分用到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

下面兩個引數是防止反爬的,別的文章也是這麼寫的,但我這裡沒用到

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

# 拿到檔案對應的下載連結
def _get_files_url(self):
    # 用谷歌瀏覽器開啟
    driver=webdriver.Chrome()
    # 拿到url
    driver.get(self.url)
    print(driver.title)
    time.sleep(5)
    # 通過標籤id拿到對應操作物件
    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語法寫的標籤很煩。。。我這裡先找到目標標籤的父標籤
    # 然後通過父標籤拿到目標標籤
    dd=driver.find_elements_by_class_name('col-xs-2')
    # 我這個父標籤下有兩個<a></a>標籤,只能要第一個
    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
    # 建立一個儲存zip的資料夾
    # 更改執行路徑的原因是這樣可以靈活的在使用者指定的目錄下建立檔案
    os.chdir(self.file_path)
    if os.path.exists(self.file_path+'/'+'Download_Files') == False:
        os.mkdir('Download_Files')
    # 更改執行路徑
    os.chdir(self.file_path + '/'+'Download_Files/')
    for url in url_list:
        # 連結中附帶了作者和檔名,但是需要解碼,所以先用正則語言提取目標串,然後轉換成中文
        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()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
解釋
用selenium庫訪問目標頁面,我這裡通過_get_files_url方法定位輸入框和超連結地址,然後返回超連結地址。之後在download_save方法內通過request.get拿到檔案,然後存在本地,裡面的一些存放目錄、檔名處理等細節看程式碼就可以了。
注意,這只是一個案例,不具備普適性,因為每個頁面的前端編寫方法不盡相同,具體頁面需要具體分析,我這裡不貼我的網站是涉及到女朋友的業務,所以不適合貼。

提取內容並填寫
使用到的庫
這部分用到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

# 解壓出目標檔案
def _unzip_files(self):
    '''
    這個函式具備解壓目標檔案的功能並且返回需要處理的檔案列表
    :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:
            # 程式碼有點長,主要是用於篩選出目標檔案
            target_file=list(filter(lambda x:re.search(r'比對報告.html$',x)!=None,z.namelist()))
            # 下面的方法就是比較靈活的
            contentb=z.read(target_file[0])
            # 這裡很頭痛的一點是返回值是二進位制的,就算decode了也沒辦法正則匹配
            # 所以我想把它存一下再用utf8格式讀取
            # 當然我也嘗試了decode,但網頁內的有些東西還是沒辦法轉換,也會導致正則無法匹配
            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檔案內容
def read_html(self):
    '''
    之前的函式已經把目標檔案解壓出來了,但html檔案的讀取比較麻煩,
    所以這裡用到了BeautifulSoup庫來讀取我想要的資訊,
    然後把想要的東西存在列表裡面返回回來。
    :return:
    '''
    files_list,title_list=self._unzip_files()
    repetition_rate=[]
    for file in files_list:
        # 取出作者和標題,這兩個資料要寫到excel裡面
        file=file.split('.')
        file=file[0].split('_')
        author=file[0]
        title=file[1]
        # 比對報告已經解壓出來了,直接讀取就可以
        with open(self.file_path+'/'+title+'_比對報告.html','rb') as f:
            # 下面是BeautifulSoup的用法,看不懂的話可以去官網
            content=f.read()
            content=BeautifulSoup(content,"html.parser")
            # print(type(content))
            # 網上搜了很多,終於可以找到我想要的重複率了
            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')
    # 設定邊框
    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
    # 設定背景顏色,這些操作搞得很像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()
    # 寫一個標題
    booksheet.write(0,0,'作者',style)
    booksheet.write(0,1,'標題',style)
    booksheet.write(0,2,'重複率',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='重複率.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()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
解釋
由於我下載的zip檔案,這就需要先解壓,解壓的庫是zipfile,當然這種解壓只是在執行的時候解開,不是實際解壓到目錄下面的。解壓出來的檔案比較冗雜,所以我用正則匹配了一個最合適(能夠減少編寫工作量)的檔案,這部分程式碼中的大部分工作都是為了拿到我的目標值(其中包括位元組流和字串的轉換工作,我就是失敗了才會選擇儲存html檔案並重新讀取資訊的多餘過程),也就是(作者,標題,repetition rate),資訊寫入excel的過程倒不是很複雜。我基本上沒有解釋方法是因為這些百度一下或者看官網就行了,主要還是闡述一下我的編寫思路

後續發現的問題
zipfile的亂碼問題
修改程式碼的時候我發現zipfile並不是很好用,針對某些zip檔案做操作的時候,zipfile.Zipfile.extract方法解壓會導致亂碼,我在網上也搜到瞭解決方案,一種是不修改原始碼,對檔案重新命名(我自己用了,但會導致出現兩個資料夾,且其中一個是未改名的亂碼狀態);另外一種是修改原始碼,這種方法目前還沒碰到什麼問題,用起來也挺方便的。參考的文章連結我也同樣放在後面。
參考文章
Excel的操作:
Python3讀取和寫入excel表格資料.
BeautifulSoup的操作:
Python使用beautifulSoup獲取標籤內資料.
selenium的操作:
selenium之 定位以及切換frame(iframe).
Python Selenium庫的使用.
zip檔案的解壓和讀取和亂碼問題:
Python讀寫zip壓縮檔案.
使用 zipfile 解壓含有中文檔名的 zip 檔案,不修改原始碼.
針對亂碼:修改zipfile原始碼的方法.