1. 程式人生 > >python 爬蟲將所爬到的資料儲存在檔案中

python 爬蟲將所爬到的資料儲存在檔案中

Python 爬蟲,將所爬到的資料儲存在.txt檔案中

import urllib.request
import re
response = urllib.request.urlopen("https://search.51job.com/list/010000%252C020000%252C030200%252C040000,000000,0000,00,9,99,python,2,1.html")
#url為將來要爬去的資料的來源網址
html = response.read()
html = html.decode("GBK")
#decode將爬到的資料編碼方式改變
lst = re. findall('<span class="t3">(北京|上海|廣州|深圳).*</span>\s*<span class="t4">(\d*\.?\d*)-(\d*\.?\d*)(\w)/(.*)</span>',html)
#正則表示式是匹配所要爬去資料的關鍵,根據所要爬取的資料寫出正確的正則表示式
file = open("D:\\1.txt","w")
for i  in lst:
    min = float(i[1])
    max = float(i[2])
    if  i[3] == "千":
        min /= 10
        max /= 10
    if  i[4] == "年":
        min /= 12
        max /= 12
    file.write("%s\t%s\t%.2f\t%.2f\t%s\t" % ("Python",i[0],min,max,"萬/月"))
    file.write("\n")
#單位轉換
file.close()