爬虫3_获取汇率数据

本文介绍了如何使用Python爬虫分别从三个网站抓取美元、英镑和欧元对人民币的汇率数据,并通过解析网页、数据格式转换后存储到MySQL数据库中。爬取过程包括导入相关包、获取网页数据、调整日期格式以及将数据存入数据库。

1 爬取的内容

根据需要美元,英镑,以及欧元对人民币的汇率,网站比较简单。分为三个网站,地址如下,获取当日页面里的数据,没有太多复杂的解析。三个网站的规则是一样的,里面的解析方法也和步骤也是相同的。
欧元对人民币
英镑对人民币
美元对人民币

1.1 爬取的界面

在这里插入图片描述
网页右键点击,选择检查,查看网页代码,找到标题和对应数据所在的位置,下面就进行相关数据的获取在这里插入图片描述

2 爬取的过程

2.1 导入需要的包

a0_mysql是我上一个文章里, 爬虫2_python连接mysql数据库代码,主要是连接数据库,将获取到的数据直接导入到数据库里。

# coding: utf-8
from pathlib import Path
import os
import pandas as pd
import requests
from bs4 import BeautifulSoup
import warnings
warnings.filterwarnings('ignore')
import os
from a0_mysql import del_sql,get_sql_data,to_sql
# 可以自定义代理,一般本地使用就没有用到代理,如果是一些工作内容或者其他内网需要开通,会需要个代理。
proxies = {'http': "http://代理地址", 'https': 'https://代理地址'}

2.2 获取网页数据

'''
输入:
url:     网页地址
headers:  一般的头部信息
proxn:    是否使用代理,如果是true,则使用代理

输出:     如1.1中的表格里的数据
'''
def get_data(url, headers , proxn):
	# 是否使用代理
    if proxn =='true':
        req = requests.get(url=url, headers=headers, proxies=proxies)
    else:
        req = requests.get(url=url, headers=headers)
    soup = BeautifulSoup(req.text, 'lxml')
    # 在检查中找到数据存放在 该class value 下
    body = soup.find_all(class_='genTbl closedTbl historicalTbl')[0].find_all('tr')
    s = []
    for  j  in range(len(body)):
        a = [i for i in body[j].text.split('\n')  if i!='']
        s.append(a)
    data = pd.DataFrame(s[1:],columns=s[0])
    return data

简单的进行调用

head ={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'}
proxn = 'false'# 不使用代理
url_usd = 'https://cn.investing.com/currencies/usd-cny-historical-data'  # 美元
df_usd  = get_data(url_usd, head, proxn)

结果如下:
在这里插入图片描述

2.3 数据格式更改

鉴于需要将时间里的年月日,改为横线,即2020年1月1日改为2020-01-01。 python里关于时间的处理也是很多种技巧和方法。这里写了一个傻瓜式的更改。

def trans(a):
    a = a.replace('年', "-")
    a = a.replace('月', "-")
    a = a.replace('日', "")
    a1 = a.split('-')[0]
    a2 = a.split('-')[1]
    a3 = a.split('-')[2]

    if len(str(a2)) < 2:
        a2 = '0' + str(a2)
    else:
        a2 = str(a2)

    if len(str(a3)) < 2:
        a3 = '0' + str(a3)
    else:
        a3 = str(a3)
    a = a1 + '-' + a2 + '-' + a3
    return a

经过处理后的数据如下所示:
在这里插入图片描述

2.4 获取所有数据并传入数据库

获取美元,英镑以及欧元对人民币的数据。并将更改时间后的数据存入到mysql数据库中。

def today(headers, sheet_name, proxn):
    url_usd = 'https://cn.investing.com/currencies/usd-cny-historical-data'  # 美元
    url_gbp = 'https://cn.investing.com/currencies/gbp-cny-historical-data'  # 英镑
    url_eur = 'https://cn.investing.com/currencies/eur-cny-historical-data'  # 欧元

    df_usd  = get_data(url_usd, headers,proxn)
    df_gbp = get_data(url_gbp, headers,proxn)
    df_eur = get_data(url_eur, headers,proxn)

    df_usd['币种'] = 'USD_CNY'
    df_gbp['币种'] = 'GBP_CNY'
    df_eur['币种'] = 'EUR_CNY'

    df_usd['日期'] = [trans(i) for i in df_usd['日期']]
    df_gbp['日期'] = [trans(i) for i in df_gbp['日期']]
    df_eur['日期'] = [trans(i) for i in df_eur['日期']]

    df_usd['涨跌幅'] = [round(0.01 * float(i.replace('%', '')), 6) for i in df_usd['涨跌幅']]
    df_gbp['涨跌幅'] = [round(0.01 * float(i.replace('%', '')), 6) for i in df_gbp['涨跌幅']]
    df_eur['涨跌幅'] = [round(0.01 * float(i.replace('%', '')), 6) for i in df_eur['涨跌幅']]

    today_usd = tuple(df_usd['日期'].unique().tolist())
    today_gbp = tuple(df_gbp['日期'].unique().tolist())
    today_eur = tuple(df_eur['日期'].unique().tolist())

    '''1 删除数据库中这些日期的数据'''
    sql2_usd = """ DELETE from pur_汇率 WHERE  币种 = 'USD_CNY'and 日期  IN {0}""".format(today_usd)
    sql2_gbp = """ DELETE from pur_汇率 WHERE  币种 = 'GBP_CNY'and 日期  IN {0}""".format(today_gbp)
    sql2_eur = """ DELETE from pur_汇率 WHERE  币种 = 'EUR_CNY'and 日期  IN {0}""".format(today_eur)
    del_sql(sql2_usd)
    del_sql(sql2_gbp)
    del_sql(sql2_eur)

    '''2 数据存入'''
    to_sql(df_usd,sheet_name)
    to_sql(df_gbp,sheet_name)
    to_sql(df_eur,sheet_name)

如上是爬取的所有过程。代码存放github的地址:c1_汇率

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值