python 製作網站篩選工具(附原始碼)
阿新 • • 發佈:2021-01-21
一.思路
1.整體思路
2.程式碼思路
思路很簡單,就是用python傳送請求,提取響應體中的狀態碼加以判斷,最後儲存到本地txt文字中,以實現網站資訊的篩選。
二.撰寫程式碼
import time import requests import urllib3 from concurrent.futures import ThreadPoolExecutor #取原始檔中的網址並且去重 def get_url(old_file): with open(old_file,'r',encoding='gbk')as f: urllist=list(set(f.readlines())) return urllist #主體,傳送請求,通過異常捕獲判斷能否響應,通過狀態碼判斷網閘能否正常訪問 def request(url): url=url.strip() #構造請求頭資訊 headers = { 'Connection': 'keep-alive','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/78.0.3904.108 Safari/537.36' } try: #忽略證書安全警告 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) r=requests.get(url,headers=headers,timeout=10,verify=False)#timeout設定超時時間,我設定了10s,使用verif=False忽略sll認證 if r.status_code==200: cost_time=r.elapsed.total_seconds()#計算訪問耗時 print(url,' ----->【能訪問】訪問耗時:\033[35;46m{:.2f}s\033[0m'.format(cost_time)) can_access_save_to_txt(url) else: print(url,' ----->不能訪問,狀態碼為:\033[31;44m{}\033[0m'.format(r.status_code)) except: print(url,原因:\033[31;44m不能響應\033[0m') #將能訪問的網址儲存到new_file def can_access_save_to_txt(result): result=result.strip() #篩選出不是.apk的url,此判斷可以不加 if not result.endswith('.apk'): with open(aim_file,'a')as f: f.write(result+'\n') def main(): s_time=time.time() #使用執行緒池,建立四條執行緒。 pool=ThreadPoolExecutor(max_workers=4) urls=get_url(orign_file) for url in urls: pool.submit(request,url) pool.shutdown() e_time=time.time() sum_time=int(e_time-s_time) if sum_time>60: print(f'\033[38;46m 程式正常執行結束退出!共耗時:【{sum_time//60}分鐘】 \033[0m') elif sum_time/60>1: print(f'\033[38;46m 程式正常執行結束退出!共耗時:【{sum_time//60*60}小時】 \033[0m') if __name__ == '__main__': orign_file=r'E:\test.txt' #篩選後能訪問的網址 aim_file="./data/test_can_access.txt" #篩選後不能訪問的網址 main()
三.執行結果
四.總結
本次使用python撰寫了一款篩選網站的小工具,將網站大致分為能訪問和不能訪問兩類,將能夠訪問且狀態碼為200的網站儲存到了檔案中,最終實現了網站的篩選。思路、程式碼方面有什麼不足歡迎各位大佬指正、批評!
以上就是python 製作網站篩選工具(附原始碼)的詳細內容,更多關於python 製作網站篩選工具的資料請關注我們其它相關文章!