使用python實現(xiàn)抓取中國銀行外匯牌價首頁數(shù)據(jù)實現(xiàn)
利用requests、BeautifulSoup、xlwings庫抓取中國銀行外匯牌價首頁數(shù)據(jù)
1. 利用requests、BeautifulSoup、xlwings庫抓取中國銀行外匯牌價首頁數(shù)據(jù)。
(1)中國銀行外匯牌價網(wǎng)址如下。
https://www.bankofchina.com/sourcedb/whpj/
(2)調(diào)用requests模塊中get方法訪問上述網(wǎng)址,獲取Response 對象。
url = "https://www.bankofchina.com/sourcedb/whpj/" web=re.get(url)
(3)利用BeautifulSoup類解析。
#BeautifulSoup將字節(jié)流轉(zhuǎn)換為utf-8編碼 bs_obj=BeautifulSoup(web.text,'lxml')
(4)利用find_all方法查找table、tr、td等標簽對象。
#查找數(shù)據(jù)所在表格
table=bs_obj.find_all('table')[1] all_th=all_tr.find_all('th') #print(all_th) all_td=all_tr.find_all('td') #print(all_td)
(5)將找到的相應標簽內(nèi)容依次添加到列表中。
if len(all_th)>0: dataRow=[] for item in all_th: dataRow.append(item.text) dataAll.extend([dataRow]) if len(all_td)>0: dataRow=[] for item in all_td: dataRow.append(item.text) dataAll.extend([dataRow])
(6)利用xlwings庫,將列表內(nèi)容寫入Excel文件。
wb=xw.Book() sht=wb.sheets('Sheet1') sht.range('a1').value=dataAll#將數(shù)據(jù)添加到表格中
(7)利用這部分數(shù)據(jù)建立折線圖。
chart=sht.charts.add(500,50,700,400) chart.set_source_data(sht.range('A1:A28,C1:C28,E1:E28'))#設置數(shù)據(jù)畫圖 chart.chart_type='line_markers' chart.name='line_markersd' #chart.api[1].ChartTitle.Text='中國銀行外匯牌價'
Code:
import requests as re from bs4 import BeautifulSoup import xlwings as xw url = "https://www.bankofchina.com/sourcedb/whpj/" web=re.get(url) web.encoding=web.apparent_encoding #BeautifulSoup將字節(jié)流轉(zhuǎn)換為utf-8編碼 bs_obj=BeautifulSoup(web.text,'lxml') #查找數(shù)據(jù)所在表格 table=bs_obj.find_all('table')[1] #print(table) dataAll=[] for all_tr in table.find_all('tr'):#找到所有tr,返回一個列表 all_th=all_tr.find_all('th') #print(all_th) all_td=all_tr.find_all('td') #print(all_td) if len(all_th)>0: dataRow=[] for item in all_th: dataRow.append(item.text) dataAll.extend([dataRow]) if len(all_td)>0: dataRow=[] for item in all_td: dataRow.append(item.text) dataAll.extend([dataRow]) wb=xw.Book() sht=wb.sheets('Sheet1') sht.range('a1').value=dataAll#將數(shù)據(jù)添加到表格中 chart=sht.charts.add(500,50,700,400) chart.set_source_data(sht.range('A1:A28,C1:C28,E1:E28'))#設置數(shù)據(jù)畫圖 chart.chart_type='line_markers' chart.name='line_markersd' #chart.api[1].ChartTitle.Text='中國銀行外匯牌價'
以上就是使用python實現(xiàn)抓取中國銀行外匯牌價首頁數(shù)據(jù)實現(xiàn)的詳細內(nèi)容,更多關于Python抓取中國銀行外匯牌價的資料請關注本站其它相關文章!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。