BeautifulSoup可以使我們通過網頁的標簽找到網頁中我們想要的特定數據。本案例可以清楚地理順從html文件變化到我們想要獲得的數據。Python程序如下:
from bs4 import BeautifulSoupimport requestsurl = 'http://new.cpc.com.tw/division/mb/oil-more4.aspx'html = requests.get(url).textbs = BeautifulSoup(html, 'html.parser')#PRint(bs)data = bs.find_all('span' ,{'id':'Showtd'} )#print(data)rows = data[0].find_all('tr')#print(rows)prices = list()i = 0for row in rows: if i < 16: print(row) 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 += 1i = 0for p in prices: if i < 16: print(p) i += 1現在從變量容器的變化過程,認識提取特定數據的步驟:通過BeautifulSoup(html, 'html.parser'),把html文件包裝為可以解析的對象,該對象對應的文本文件(部分內容)是:2.操作可解析的對象sb,通過find_all('span',{'id':'Showtd'}),把標簽<span></span>的內容找出來,形成數據表:
3.再從上面的數據表中,找出標簽<tr></tr>表示的項,組成如下表:
4.對上表的每個表項<td></td>再進行提取,得到最終數據:
新聞熱點
疑難解答