脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python自动打开浏览器下载zip并提取内容写入excel

python自动打开浏览器下载zip并提取内容写入excel

2021-08-21 00:32拯救自己的小毛猴 Python

这篇文章主要给大家介绍了关于python自动打开浏览器下载zip并提取内容写入excel的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

佬们轻喷,里面有些代码都是现学现写的,一些细节没处理好的地方还请指出来~~~

首先贴上效果图:有些部分我没有放进来,比如浏览器的启动,但我详细聪明的你们那个玩意肯定一学就会。有些东西我没放进来

python自动打开浏览器下载zip并提取内容写入excel

下载

使用到的库和总体思路

这部分用到time,selenium,urllib,re,requests,os这几个库。

代码

  1. #!/usr/bin/python3
  2. # coding=utf-8
  3. import time
  4. from selenium import webdriver
  5. from urllib.parse import quote,unquote
  6. import re
  7. import requests
  8. import os
  9. # 下面两个参数是防止反爬的,别的文章也是这么写的,但我这里没用到
  10. headers = {
  11. 'Accept': '*/*',
  12. 'Accept-Language': 'en-US,en;q=0.5',
  13. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
  14. }
  15. params = {
  16. 'from': 'search',
  17. 'seid': '9698329271136034665'
  18. }
  19.  
  20. class Download_file():
  21. def __init__(self,url,order_number,file_path):
  22. self.url=url
  23. self.order_number=order_number
  24. self.file_path=file_path
  25.  
  26. # 拿到文件对应的下载链接
  27. def _get_files_url(self):
  28. # 用谷歌浏览器打开
  29. driver=webdriver.Chrome()
  30. # 拿到url
  31. driver.get(self.url)
  32. print(driver.title)
  33. time.sleep(5)
  34. # 通过标签id拿到对应操作对象
  35. driver.switch_to.frame(0)
  36. driver.find_element_by_id('search_id').send_keys(self.order_number)
  37. # 具体页面有具体的操作,这里我需要找的button没有id,他是用ng-click="queryCheckRecordByTid(queryInfo.queryTid)"
  38. driver.find_element_by_class_name('btn').click()
  39. # driver.find_element_by_id('su').click()
  40. time.sleep(3)
  41. # AngularJS语法写的标签很烦。。。我这里先找到目标标签的父标签
  42. # 然后通过父标签拿到目标标签
  43. dd=driver.find_elements_by_class_name('col-xs-2')
  44. # 我这个父标签下有两个<a></a>标签,只能要第一个
  45. url_list=[]
  46. for i in dd:
  47. # 因为下载的url正好是第一个,然后这里取得是element,所以正好取到正确的url
  48. a=i.find_element_by_xpath('.//a')
  49. # print(a.get_attribute('href'))
  50. url_list.append(a.get_attribute('href'))
  51. # download_btn[0].click()
  52. time.sleep(3)
  53. driver.close()
  54. return url_list
  55.  
  56. # 下载文件
  57. def download_save(self):
  58. # 匹配出来的可能有None,所以要做一下处理
  59. url_list=self._get_files_url()
  60. url_list=list(filter(lambda x:x!=None,url_list))
  61. if len(url_list)==0:
  62. return False
  63. # 创建一个保存zip的文件夹
  64. # 更改执行路径的原因是这样可以灵活的在用户指定的目录下创建文件
  65. os.chdir(self.file_path)
  66. if os.path.exists(self.file_path+'/'+'Download_Files') == False:
  67. os.mkdir('Download_Files')
  68. # 更改执行路径
  69. os.chdir(self.file_path + '/'+'Download_Files/')
  70. for url in url_list:
  71. # 链接中附带了作者和文件名,但是需要解码,所以先用正则语言提取目标串,然后转换成中文
  72. ret = re.search(r'_.*\.zip$',url)
  73. file_info=unquote(ret.group())
  74. file_author=file_info.split('_')[1]
  75. file_title=file_info.split('_')[2]
  76. file_object=requests.get(url)
  77. file_name=file_author+'_'+file_title
  78. print('正在下载:%s'%file_name)
  79. with open(file_name,'wb') as f:
  80. f.write(file_object.content)
  81.  
  82. # def auto_fill(self):
  83.  
  84. if __name__ == '__main__':
  85. url='http://***'
  86. order_id='***'
  87. file_path='D:/For discipline/Get_excel'
  88. test=Download_file(url,order_id,file_path)
  89. test.download_save()

解释

用selenium库访问目标页面,我这里通过_get_files_url方法定位输入框和超链接地址,然后返回超链接地址。之后在download_save方法内通过request.get拿到文件,然后存在本地,里面的一些存放目录、文件名处理等细节看代码就可以了。
注意,这只是一个案例,不具备普适性,因为每个页面的前端编写方法不尽相同,具体页面需要具体分析,我这里不贴我的网站是涉及到女朋友的业务,所以不适合贴。

提取内容并填写

使用到的库

这部分用到time,xlwt,urllib,re,pickle,os,zipfile,BeautifulSoup这几个库。

代码

  1. #!/usr/bin/python3
  2. # coding=utf-8
  3. import os
  4. import time
  5. import xlwt
  6. import zipfile
  7. import re
  8. import pickle
  9. from bs4 import BeautifulSoup
  10. from Download_files import Download_file
  11. class get_excel():
  12. def __init__(self,file_path):
  13. self.file_path=file_path
  14.  
  15. # 解压出目标文件
  16. def _unzip_files(self):
  17. '''
  18. 这个函数具备解压目标文件的功能并且返回需要处理的文件列表
  19. :return:
  20. '''
  21. files_list=os.listdir(self.file_path)
  22. # 文件名存放在列表中,为了防止处理了别的文件,先用正则匹配一下
  23. files_list=list(filter(lambda x:re.search(r'\.zip$',x)!=None,files_list))
  24. title_list=[]
  25. for file in files_list:
  26. title=file.split('.')[0].split('_')[1]
  27. with zipfile.ZipFile(self.file_path+'/'+file,'r') as z:
  28. # 代码有点长,主要是用于筛选出目标文件
  29. target_file=list(filter(lambda x:re.search(r'比对报告.html$',x)!=None,z.namelist()))
  30. # 下面的方法就是比较灵活的
  31. contentb=z.read(target_file[0])
  32. # 这里很头痛的一点是返回值是二进制的,就算decode了也没办法正则匹配
  33. # 所以我想把它存一下再用utf8格式读取
  34. # 当然我也尝试了decode,但网页内的有些东西还是没办法转换,也会导致正则无法匹配
  35. if os.path.exists(self.file_path+'/'+title+'_'+'比对报告.html')==False:
  36. with open(self.file_path+'/'+title+'_'+'比对报告.html','wb') as fb:
  37. pickle.dump(contentb,fb)
  38. # with open(self.file_path+'/'+target_file[0],'r',encoding='utf-8') as fa:
  39. # contenta=fa.read()
  40. # print(contenta)
  41. # sentence=str(re.search(r'<b [^"]*red tahoma.*</b>$',contenta))
  42. # value=re.search(r'\d.*%', sentence)
  43. # info=[author,title,value]
  44. # repetition_rate.append(info)
  45. title_list.append(target_file[0])
  46. return files_list,title_list
  47.  
  48. # 读取html文件内容
  49. def read_html(self):
  50. '''
  51. 之前的函数已经把目标文件解压出来了,但html文件的读取比较麻烦,
  52. 所以这里用到了BeautifulSoup库来读取我想要的信息,
  53. 然后把想要的东西存在列表里面返回回来。
  54. :return:
  55. '''
  56. files_list,title_list=self._unzip_files()
  57. repetition_rate=[]
  58. for file in files_list:
  59. # 取出作者和标题,这两个数据要写到excel里面
  60. file=file.split('.')
  61. file=file[0].split('_')
  62. author=file[0]
  63. title=file[1]
  64. # 比对报告已经解压出来了,直接读取就可以
  65. with open(self.file_path+'/'+title+'_比对报告.html','rb') as f:
  66. # 下面是BeautifulSoup的用法,看不懂的话可以去官网
  67. content=f.read()
  68. content=BeautifulSoup(content,"html.parser")
  69. # print(type(content))
  70. # 网上搜了很多,终于可以找到我想要的重复率了
  71. value=content.find('b',{"class":"red tahoma"}).string
  72. repetition_rate.append([author,title,value])
  73. return repetition_rate
  74.  
  75. def write_excel(self):
  76. '''
  77. 生成xls表格
  78. :return:
  79. '''
  80. workbook=xlwt.Workbook(encoding='utf-8')
  81. booksheet=workbook.add_sheet('Sheet1')
  82. # 设置边框
  83. borders = xlwt.Borders() # Create Borders
  84. borders.left = xlwt.Borders.THIN #DASHED虚线,NO_LINE没有,THIN实线
  85. borders.right = xlwt.Borders.THIN #borders.right=1 表示实线
  86. borders.top = xlwt.Borders.THIN
  87. borders.bottom = xlwt.Borders.THIN
  88. borders.left_colour=0x40
  89. borders.right_colour = 0x40
  90. borders.top_colour = 0x40
  91. borders.bottom_colour = 0x40
  92. style1=xlwt.XFStyle()
  93. style1.borders=borders
  94. # 设置背景颜色,这些操作搞得很像js和css
  95. pattern = xlwt.Pattern()
  96. pattern.pattern = xlwt.Pattern.SOLID_PATTERN
  97. pattern.pattern_fore_colour = 44
  98. style = xlwt.XFStyle() # Create the Pattern
  99. style.pattern = pattern
  100. repetition_rate=self.read_html()
  101. # 写一个标题
  102. booksheet.write(0,0,'作者',style)
  103. booksheet.write(0,1,'标题',style)
  104. booksheet.write(0,2,'重复率',style)
  105. for item in repetition_rate:
  106. booksheet.write(repetition_rate.index(item)+1,0,item[0],style1)
  107. booksheet.write(repetition_rate.index(item)+1,1,item[1],style1)
  108. booksheet.write(repetition_rate.index(item)+1,2,item[2],style1)
  109. s='重复率.xls'
  110. workbook.save(self.file_path+'/'+s)
  111.  
  112. if __name__ == '__main__':
  113. # 判断一下Download_files文件夹
  114. file_path='D:/For discipline/Get_excel'
  115. url='http://***'
  116. order_number='***'
  117. if os.path.exists('./Download_Files')==False:
  118. get_file=Download_file(url,order_number,file_path)
  119. get_file.download_save()
  120. os.chdir(file_path+'/Download_Files')
  121. test=get_excel('D:/For discipline/Get_excel/Download_Files')
  122. test.write_excel()

解释

由于我下载的zip文件,这就需要先解压,解压的库是zipfile,当然这种解压只是在执行的时候解开,不是实际解压到目录下面的。解压出来的文件比较冗杂,所以我用正则匹配了一个最合适(能够减少编写工作量)的文件,这部分代码中的大部分工作都是为了拿到我的目标值(其中包括字节流和字符串的转换工作,我就是失败了才会选择保存html文件并重新读取信息的多余过程),也就是(作者,标题,repetition rate),信息写入excel的过程倒不是很复杂。我基本上没有解释方法是因为这些百度一下或者看官网就行了,主要还是阐述一下我的编写思路

附:Python使用beautifulSoup获取标签内数据

  1. from bs4 import BeautifulSoup
  2.  
  3. for k in soup.find_all('a'):
  4. print(k)
  5. print(k['class'])#查a标签的class属性
  6. print(k['id'])#查a标签的id
  7. print(k['href'])#查a标签的href
  8. print(k.string)#查a标签的string
  9. #tag.get('calss'),也可以达到这个效果

到此这篇关于python自动打开浏览器下载zip并提取内容写入excel的文章就介绍到这了,更多相关python自动浏览器下载zip并提取内容内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

参考文章

  • Excel的操作: Python3读取和写入excel表格数据.
  • selenium的操作: selenium之 定位以及切换frame(iframe) . Python Selenium库的使用.
  • zip文件的解压和读取:Python读写zip压缩文件.

原文链接:https://blog.csdn.net/Savingme/article/details/112143595

延伸 · 阅读

精彩推荐