使用python实现抓取中国银行外汇牌价首页数据实现
利用requests、BeautifulSoup、xlwings库抓取中国银行外汇牌价首页数据
1. 利用requests、BeautifulSoup、xlwings库抓取中国银行外汇牌价首页数据。
(1)中国银行外汇牌价网址如下。
https://www.bankofchina.com/sourcedb/whpj/
(2)调用requests模块中get方法访问上述网址,获取Response 对象。
url = "https://www.bankofchina.com/sourcedb/whpj/" web=re.get(url)
(3)利用BeautifulSoup类解析。
#BeautifulSoup将字节流转换为utf-8编码 bs_obj=BeautifulSoup(web.text,'lxml')
(4)利用find_all方法查找table、tr、td等标签对象。
#查找数据所在表格
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)将找到的相应标签内容依次添加到列表中。
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库,将列表内容写入Excel文件。
wb=xw.Book() sht=wb.sheets('Sheet1') sht.range('a1').value=dataAll#将数据添加到表格中
(7)利用这部分数据建立折线图。
chart=sht.charts.add(500,50,700,400) chart.set_source_data(sht.range('A1:A28,C1:C28,E1:E28'))#设置数据画图 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将字节流转换为utf-8编码 bs_obj=BeautifulSoup(web.text,'lxml') #查找数据所在表格 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#将数据添加到表格中 chart=sht.charts.add(500,50,700,400) chart.set_source_data(sht.range('A1:A28,C1:C28,E1:E28'))#设置数据画图 chart.chart_type='line_markers' chart.name='line_markersd' #chart.api[1].ChartTitle.Text='中国银行外汇牌价'
以上就是使用python实现抓取中国银行外汇牌价首页数据实现的详细内容,更多关于Python抓取中国银行外汇牌价的资料请关注本站其它相关文章!
版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。