from urllib.request import urlopen
import re
from bs4 import BeautifulSoup
f = open('News_MIUIROM.txt','w',encoding='utf-8') #打印ROM版本到News_MIUIROM.txt文檔
j = 330
#獲取URL方法
def get_url():
? ? url = 'http://www.miui.com/download-'+str(j+x)+'.html'
? ? return url
#獲取ROM信息方法
def get_romnews():
? ? html = urlopen(get_url())? # 訪問小米ROM網址
? ? content = html.read().decode('utf-8')? #以utf-8 字節碼編譯 網頁信息
? ? content = BeautifulSoup(content, 'html.parser') #bs4對網頁編碼進行整理
? ? content = content.find_all("a", class_="route_a d2r") #獲取ROM信息
? ? content = str(content)? #轉化成字符串
? ? Rom_download = re.search('http(.*?)zip',content).group(0) #使用正則表達式截取ROM下載地址
? ? print(Rom_download)
? ? Rom_version= re.search('m/(.*?)/m',Rom_download).group(1) #獲取ROM版本信息
? ? print(Rom_version)
? ? return Rom_download,Rom_version
#循環寫入ROM信息
for x in range(0,10):
? ? try:
? ? ? ? a ,b = get_romnews()
? ? except AttributeError:
? ? ? ? print('無此網頁')? #異常處理
? ? ? ? continue
? ? else:
? ? ? ? f.write('ROM下載地址:' + a + '\n')
? ? ? ? f.write('ROM版本信息:' + b + '\n')
f.close()