Python抓取中国银行外汇牌价 使用python实现抓取中国银行外汇牌价首页数据实现

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python抓取中国银行外汇牌价 使用python实现抓取中国银行外汇牌价首页数据实现

BoBo啵啵   2021-10-28 我要评论
想了解使用python实现抓取中国银行外汇牌价首页数据实现的相关内容吗,BoBo啵啵在本文为您仔细讲解Python抓取中国银行外汇牌价的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python抓取中国银行外汇牌价,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='中国银行外汇牌价'

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们