為了把從網(wǎng)頁(yè)中解析的數(shù)據(jù)存儲(chǔ)起來(lái),便于存檔和查詢(xún),可以把數(shù)據(jù)存放在數(shù)據(jù)庫(kù)中,也可以以文件的方式存儲(chǔ),還可以存儲(chǔ)為網(wǎng)絡(luò)應(yīng)用程序,即html文件或者CSV格式文件。本文引用一個(gè)例子,看看如何將網(wǎng)頁(yè)的解析數(shù)據(jù)存儲(chǔ)為html文件。
from bs4 import BeautifulSoupimport requests#前置標(biāo)簽PRe_html = '''<!DOCTYPE HTML><html><head><!--meta charset = 'utf-8'--><title>油價(jià)歷史數(shù)據(jù)</title></head><body><h2>自去年11月份以來(lái)的油價(jià)數(shù)據(jù)(取自本例網(wǎng)站)</h2><table width=600 border=1><tr><td>日期</td><td>92#無(wú)鉛</td><td>95#無(wú)鉛</td><td>98#無(wú)鉛</td></tr>'''#后置標(biāo)簽post_html = """</table></body></html>"""url = 'http://new.cpc.com.tw/division/mb/oil-more4.aspx'src = requests.get(url)#src.encoding = "bgk"html = src.textbs = BeautifulSoup(html, 'html.parser')data = bs.find_all('span' ,{'id':'Showtd'} )rows = data[0].find_all('tr')prices = list()i = 0for row in rows: if i > 18:break; cols = row.find_all("td") if len(cols[1].text ) > 0: item = [cols[0].text, cols[1].text, cols[2].text, cols[3].text] prices.append(item) i += 1#生成數(shù)據(jù)表html_body = ''for p in prices: html_body += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>".format(p[0],p[1],p[2],p[3])html_file = pre_html + html_body + post_html#按文本文件的方式生成html文件fp = open('oilprice.html','w')fp.write(html_file)fp.close()用瀏覽器打開(kāi)執(zhí)行的結(jié)果:
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注