华域联盟 Python 使用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='中国银行外汇牌价'

以上就是使用python实现抓取中国银行外汇牌价首页数据实现的详细内容,更多关于Python抓取中国银行外汇牌价的资料请关注华域联盟其它相关文章!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » 使用python实现抓取中国银行外汇牌价首页数据实现

转载请保留出处和原文链接:https://www.cnhackhy.com/40802.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部