一、中文 對齊問題願意
: <填充> <對齊> <寬度> , <.精度> <類型>
引號 用於填充的 <左對齊 槽的設定輸出 數字的千位分割符 浮點數小數部分 整數類型b,c,
符號 單個符號 >右對齊 寬度 適用於整數和浮點 的精度或字符串 d,o,x,X浮點數
^居中對齊 數 的最大輸出長度 類型e,E,f,%
當中文字符寬度不夠時,采用西文字符進行填充;中西文字符占用寬度不同。
中文字符寬度不夠時解決方法:采用中文字符的空格填充chr(12288)
1 import requests 2 import parsel 3 4 """ 5 模擬瀏覽器進入網頁 6 獲取url的內容 7 """ 8 def get_page_url(hd,url): 9 try: 10 r =requests.get(url,headers=hd,timeout=30) 11 r.raise_for_status() #判斷返回的狀態是否是200 12 r.encoding = r.apparent_encoding #轉換編碼方式為內容分析出的相應編碼方式 13 return r.text 14 except: 15 return None 16 17 """ 18 解析頁面內容 19 使用xpath獲取有用的信息 20 """ 21 def parsing_website(html,content_list): 22 sel = parsel.Selector(html) 23 xp = sel.xpath("//tr[@class='alt']") 24 # list_from = [] 25 #使用for循環獲取需要的信息 26 for i in xp: 27 ranking= i.xpath('./td[1]/text()').get() 28 name = i.xpath('./td[2]/div/text()').get() 29 province = i.xpath('./td[3]/text()').get() 30 total_score = i.xpath('./td[4]/text()').get() 31 index = i.xpath('./td[5]/text()').get() 32 content_list.append([ranking,name,province,total_score,index]) 33 # print( content_list) 34 35 """ 36 將獲取到的信息打印出來 37 使用format方法按照一定的排序順序來打印 38 """ 39 def output_content(content_list,number): 40 output ="{0:^10}\t{1:{4}^10}\t{2:^10}\t{3:^10}" #{1:{4}^10}表示采用的填充符為format后面的第5個 41 print(output.format('排行','學校名稱','總分','指標得分',chr(12288))) #chr(12288)中文空格填充符 42 for i in range(number): 43 u = content_list[i] 44 # print(u) 45 print(output.format(u[0],u[1],u[2],u[3],chr(12288))) 46 47 if __name__ == '__main__': 48 content_list = [] 49 hd = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36' 50 } 51 url = 'http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html' 52 html = get_page_url(hd,url) 53 # print(html) 54 parsing_website(html,content_list) 55 # print(content) 56 output_content(content_list,100)