脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 使用python实现抓取中国银行外汇牌价首页数据实现

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

2022-02-20 00:16BoBo啵啵 Python

这篇文章主要为大家介绍了如何使用python实现抓取中国银行外汇牌价首页数据的实现示例,有需要的同学可以借鉴参考下,希望能够有所帮助,祝大家多多进步

利用requests、BeautifulSoup、xlwings库抓取中国银行外汇牌价首页数据

1. 利用requests、BeautifulSoup、xlwings库抓取中国银行外汇牌价首页数据。

(1)中国银行外汇牌价网址如下。

https://www.bankofchina.com/sourcedb/whpj/

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

(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://blog.csdn.net/gezongbo/article/details/120986228?utm_medium=distribute.pc_feed.none-task-blog-personrec_tag-7.nonecase&depth_1-utm_source=distribute.pc_feed.none-task-blog-personrec_tag-7.nonecase

延伸 · 阅读

精彩推荐