python門戶網站文件爬取并顯示

廣西南寧政府門面網站

import requests
import os
import io
import numpy as np
from concurrent.futures import ThreadPoolExecutor
from bs4 import BeautifulSoup
import time
import pdfplumber
import pandas as pd
from docx import Document
import docx
import win32com.client as win32
import zipfile
import xlrd
headers=[{'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'},{'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.76'}
]
temp=''
with open('D:/t.txt','r',encoding='utf-8') as f:temp=f.read()
contents=[]
def get_pdf_content(url,title):response = requests.get(url)pdf_content = io.BytesIO(response.content)with open(f'D:/{title}', 'wb') as f:f.write(pdf_content.read())print(f'D:/{title}')if 'D:/308 南寧市衛生和計劃生育委員會2018年部門預算及“三公”經費預算/308南寧市衛生和計劃生育委員會及所屬單位2018年部門預算及“三公”經費預算公開.pdf'==f'D:/{title}':return ''texts=[]with pdfplumber.open(f'D:/{title}') as pdf:for page in pdf.pages:text = page.extract_text()#提取文本texts.append(text)return ' '.join(texts)
def doc_to_docx(title):word = win32.Dispatch("Word.Application")doc = word.Documents.Open('D:\\'+title)doc.SaveAs('D:\\'+title+'x')doc.Close()word.Quit()
def get_doc_content(url,title):response = requests.get(url)pdf_content = io.BytesIO(response.content)with open(f'D:/{title}', 'wb') as f:f.write(pdf_content.read())print(f'D:/{title}')#doc_to_docx(title)texts=[]if f'D:/{title}'=='D:/市工信委2017年部門預算及“三公”經費公開.docx' or 'D:/2017年部門預算公開-政府辦公廳.docx'==f'D:/{title}' or 'D:/政務辦2017年部門預算及“三公”經費公開 (1).doc'==f'D:/{title}' or 'D:/南寧市茅橋地區人民檢察院2018年部門預算及“三公”經費預算.doc'==f'D:/{title}' or 'D:/017  南寧市審計局2018年部門預算及“三公”經費預算.doc'==f'D:/{title}' or 'D:/南寧市人大常委會辦公廳2018年部門預算及“三公”經費預算 (1).doc'==f'D:/{title}' or 'D:/2017年市民宗委預算公開 (1).doc'==f'D:/{title}' or 'D:/預算 名詞解釋.docx'==f'D:/{title}' or 'D:/南寧市編辦2017年部門預算公開名詞解釋.docx'==f'D:/{title}' or 'D:/南寧市編辦2016年決算收支增減變化情況說明.docx'==f'D:/{title}':return ''app = win32.DispatchEx("Word.Application")doc = app.Documents.Open(f'D:/{title}')content = doc.Content.Textapp.Quit()return content
def get_xls_content(url,title):response = requests.get(url)pdf_content = io.BytesIO(response.content)with open(f'D:/{title}', 'wb') as f:f.write(pdf_content.read())print(f'D:/{title}')try:  # 嘗試打開文件  with open(f'D:/{title}', 'rb') as file:passexcept Exception as e:  return ''if f'D:/{title}'=='D:/附件—市發展改革委2018年預算公開附件.xlsx' or f'D:/{title}'=='D:/2017預算公開附件-市人大.xls' or 'D:/南寧市科協2020年部門預算公開附件.xlsx'==f'D:/{title}' or 'D:/宣傳部2017年預算公開附件0309.xlsx'==f'D:/{title}':return ''if title.split('.')[-1]=='xls':df = pd.read_excel(f'D:/{title}',engine='xlrd')elif title.split('.')[-1]=='xlsx':df = pd.read_excel(f'D:/{title}',engine='openpyxl')else:return ''return df.to_string(index=False)
def solve_file(file_type,file_url,title):content=''if file_type=='pdf':content=get_pdf_content(file_url,title)elif file_type=='doc' or file_type=='docx':content=get_doc_content(file_url,title)elif file_type=='xls' or file_type=='xlsx' or file_type=='XLS':content=get_xls_content(file_url,title)return content
def unzip_file(save_file,unzip_dir_path):
# 打開壓縮包file_name=[]with zipfile.ZipFile(save_file, 'r') as zip_file:# 獲取所有文件列表for zip_info in zip_file.infolist():# 如果是文件,先將文件名從gbk編碼轉換為utf-8編碼# print(type(zip_info.filename.encode('cp437').decode('gbk').encode('utf-8')))zip_info.filename = zip_info.filename.encode('cp437').decode('gbk')# 解壓文件zip_file.extract(zip_info, unzip_dir_path)file_name.append(zip_info.filename)return file_name
def get_file(url,base,year,date):time.sleep(10)r=requests.get(url,headers=np.random.choice(headers))#利用request的get函數連接到網址if r.status_code!=200:print('connect error!')r=requests.get(url,headers=np.random.choice(headers))if r.status_code!=200:returnr.encoding='utf-8'soup = BeautifulSoup(r.text, 'html.parser')  hrefs=soup.find('div',class_='downfile').find_all('a')for href in hrefs:file_url=base+href['href']file_type=file_url.split('.')[-1]#獲取文件類型print(file_type)title=href.textif '.' not in title:title+='.'+file_typet=solve_file(file_type,file_url,title)if t!='':content=[]content.append(year)content.append(date)content.append('廣西')content.append('南寧市')content.append(title)content.append(t)content.append('預算公開')content.append(file_url)contents.append(content)print(content)elif file_type=='zip':response = requests.get(file_url)with open(f'D:/{title}', 'wb') as f:f.write(response.content)print(f'D:/{title}')if 'D:/17年預算信息公開.zip'==f'D:/{title}' or 'D:/衛計委2017年部門預算公開.zip'==f'D:/{title}':continuefile_name=unzip_file(f'D:/{title}','D:/')for name in file_name:path='D:/'+namezip_file_type=path.split('.')[-1]t=tempif zip_file_type=='xls' or zip_file_type=='xlsx' or zip_file_type=='doc' or zip_file_type=='XLS':passelse:t=solve_file(zip_file_type,'https://www.nanning.gov.cn/zwgk/fdzdgknr/czxx/sbjyjs/sbjbmys/2017bmys/P020171030399005252620.doc',name)content=[]content.append(year)content.append(date)content.append('廣西')content.append('南寧市')content.append(path.split('/')[-1])content.append(t)content.append('預算公開')content.append(file_url)contents.append(content)print(content)continueelif file_type=='rar':continuedef get_url(urls,year):#每年的總頁面time.sleep(10)r=requests.get(urls,headers=np.random.choice(headers))if r.status_code!=200:print('connect error!')r=requests.get(url,headers=np.random.choice(headers))if r.status_code!=200:returnr.encoding='utf-8'soup = BeautifulSoup(r.text, 'html.parser')  hrefs=soup.find('div',class_='nav1Cont').find_all('li')for href in hrefs:date=href.find('span',class_='time').texthref=href.find('a')base=href['href']url=base_urls+basetitle=href.text.strip()net_type=url.split('.')[-1]if net_type=='pdf':content=[]content.append(year)content.append(date)content.append('廣西')content.append('南寧市')content.append(title)t=get_pdf_content(url,title+'.pdf')if t.strip()=='':t=tempcontent.append(t)content.append('預算公開')content.append(url)contents.append(content)print(content)continueget_file(url,base_urls,year,date)for year in range(2018,2023):base_urls=f'https://www.nanning.gov.cn/zwgk/fdzdgknr/czxx/sbjyjs/sbjbmys/{year}bmys/'get_url(base_urls,year)for i in range(1,7):url=f'https://www.nanning.gov.cn/zwgk/fdzdgknr/czxx/sbjyjs/sbjbmys/{year}bmys/index_{i}.html'r=requests.get(url)if r.status_code!=200:breakget_url(url,year)df=pd.DataFrame(contents,columns=['年份','發布日期','省份','城市','標題','文本','類型','下載鏈接'])
df.to_excel('D:/廣西-南寧-部門預算2017.xlsx',index=False)

爬取網頁附件,根據文件類型分類處理,顯示文件內容并制成表格?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/209728.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/209728.shtml
英文地址,請注明出處:http://en.pswp.cn/news/209728.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

WordCount 源碼解析 Mapper,Reducer,Driver

創建包 com.nefu.mapreduce.wordcount ,開始編寫 Mapper , Reducer , Driver 用戶編寫的程序分成三個部分: Mapper 、 Reducer 和 Driver 。 ( 1 ) Mapper 階段 ? 用戶自定義的 Mapper 要繼承自己的父…

文件服務器搭建

文件服務器搭建 文件服務器有四個選擇: httpd(apache) 穩定,使用廣泛,服務器一般自帶,對于開發人員來說強烈推薦。 nginx 穩定高效,使用廣泛,linux命令可直接下載,對…

STM32CubeIDE串口空閑中斷實現不定長數據接收

STM32F051空閑中斷實現串口不定長數據接收 目的編程軟件配置串口開中斷中斷程序運行結果目的 在串口輸入不定長數據時,通過串口空閑中斷來斷幀接收數據。 編程軟件 STM32CubeIDE STM32CubeMX配置MCU。通過對端口配置,自動生成程序,減少編程量。 配置串口開中斷 配置串口…

redis中序列化問題,value包含全路徑類名解析

1. 問題 redis中保存的key-value格式 value直接存入的是實體對象,值中包含全路徑類名,在使用Jackson2JsonRedisSerializer和GenericJackson2JsonRedisSerializer解析器時報錯 報錯內容: com.fasterxml.jackson.databind.exc.InvalidTypeI…

《師兄啊師兄》第二季確認定檔!海神揚名,穩健回歸!

近日,《師兄啊師兄》第二季的定檔海報和PV終于發布,確認將于12月14日上午10點強勢回歸!這部備受矚目的國漫作品自第一季播出以來,便以其獨特的劇情設定和唯美的畫風,贏得了廣大觀眾的喜愛。如今,動畫第二季…

第一課【習題】給應用添加通知和提醒

構造進度條模板通知,name字段當前需要固定配置為downloadTemplate。 給通知設置分發時間,需要設置showDeliveryTime為false。 OpenHarmony提供后臺代理提醒功能,在應用退居后臺或退出后,計時和提醒通知功能被系統后臺代理接管…

Qt 5.15.2 三維顯示功能

Qt 5.15.2 三維顯示功能 三維顯示效果: .pro項目文件 QT core gui opengl 3dcore 3drender 3dinput 3dextrasgreaterThan(QT_MAJOR_VERSION, 4): QT widgetsCONFIG c17# You can make your code fail to compile if it uses deprecated APIs. # In ord…

2023年法國經銷商Solu-Watt來訪安科瑞-安科瑞 蔣靜

2023年4月10日上午9點,法國Solu-Watt公司Matthieu先生一行到安科瑞考察參觀工廠的智能化出入庫工作站、柔性化儀表生產車間及實驗室。自1992年以來,Solu-Watt在電氣設備市場中不斷發展。能夠提供量身定制的安裝有線電氣解決方案(電氣柜、接線…

如何用Qt配置git項目并上傳Gitee

1.進入到Qt項目文件夾內,打開 “Git Bash Here” 2.初始化,在“Git Bash Here”中輸入 git init 3.加入所有文件,在“Git Bash Here”中輸入 git add . (需要注意,git add 后面還有一個點) 4.添加備注,git com…

STL源碼剖析筆記——哈希表、unordered_set、unordered_map、unordered_mutiset、unordered_mutimap

系列文章目錄 STL源碼剖析筆記——迭代器 STL源碼剖析筆記——vector STL源碼剖析筆記——list STL源碼剖析筆記——deque、stack,queue STL源碼剖析筆記——Binary Heap、priority_queue STL源碼剖析筆記——AVL-tree、RB-tree、set、map、mutiset、mutimap STL源…

一套rk3588 rtsp服務器推流的 github 方案及記錄 -01

我不生產代碼,我只是代碼的搬運工,相信我,看完這個文章你的圖片一定能變成流媒體推出去。 訴求:使用opencv拉流,轉成bgr數據,需要把處理后的數據(BGR)編碼成264,然后推流…

字符串函數strtok

1.調用格式: 2.調用形式:char*strtok(char*p1,const char*p2),其中第二個是由分隔符組成的字符串,第一個為需要分隔的字符串 3.調用目的:將分隔符之間的字符串取出 4.調用時一般將源字符串拷貝后調用,因為此函數會將…

基于Unity3D 低多邊形地形模型紋理貼圖

在線工具推薦: 3D數字孿生場景編輯器 - GLTF/GLB材質紋理編輯器 - 3D模型在線轉換 - Three.js AI自動紋理開發包 - YOLO 虛幻合成數據生成器 - 三維模型預覽圖生成器 - 3D模型語義搜索引擎 當談到游戲角色的3D模型風格時,有幾種不同的風格&#xf…

【工程實踐】使用modelscope下載大模型文件

前言 Modelscope(魔搭社區)是阿里達摩院的一款開源模型平臺,里面提供了很多的熱門模型供使用體驗,其中的模型文件可以通過git clone 快速下載。并且為模型提供了Notebook的快速開發體驗,使用阿里云服務,不需…

【優選算法系列】【專題二滑動窗口】第三節.904. 水果成籃和438. 找到字符串中所有字母異位詞

文章目錄 前言一、水果成籃 1.1 題目描述 1.2 題目解析 1.2.1 算法原理 1.2.2 代碼編寫 1.2.3 題目總結二、找到字符串中所有字母異位詞 2.1 題目描述 2.2 題目解析 2.2.1 算法原理 2.2.2 代碼編寫 …

SAP UI5 walkthrough step9 Component Configuration

在之前的章節中,我們已經介紹完了MVC的架構和實現,現在我們來講一下,SAPUI5的結構 這一步,我們將所有的UI資產從index.html里面獨立封裝在一個組件里面 這樣組件就變得獨立,可復用了。這樣,無所什么時候我…

隊列的實現

學習就像一段長跑,比的不是誰跑得快,而是誰更能堅持!! 1 隊列的概念及結構 隊列:只允許在一端進行插入數據操作,在另一端進行刪除數據操作的特殊線性表,隊列具有先進先出 FIFO(First In First O…

外網訪問內網服務器使用教程

如何在任何地方都能訪問自己家里的筆記本上的應用?如何讓局域網的服務器可以被任何地方訪問到?有很多類似的需求,我們可以統一用一個解決方案:內網穿透。內網穿透的工具及方式有很多,如Ngrok、Ssh、autossh、Natapp、F…

linux具體命令(一)

1. cd CD命令是Linux和類Unix操作系統中非常常用的一個命令,它的全稱是“change directory”,用于改變當前的工作目錄。用戶可以通過這個命令進入到不同的目錄中,進行文件操作或是執行其他任務。 以下是CD命令的一些基本用法: 進…

特殊進程之守護進程

文章目錄 1、守護進程的概念2、如何查看守護進程3、編寫守護進程的步驟3.1 創建子進程,父進程退出3.2 在子進程中創建新會話3.3 改變當前工作目錄3.4 重設文件權限掩碼3.5 關閉不需要的文件描述符3.6 某些特殊的守護進程打開/dev/null 4、守護進程代碼示例 1、守護進…