【Day 15】- 汇率什麽的。爬! (实战汇率爬虫 on chrome)

前情提要

前一篇带各位实作了爬取 Ubuntu ISO 映像档的爬虫,并存在 JSON 档。

开始之前

本篇将带各位爬取 google 上的汇率,各位应该都有试过直接在 google chrome 搜寻美金,chrome 就会回应一个目前的汇率给你。

预期效果

输入一个币值,如果能在 chrome 上出现汇率,则让爬虫将其爬取下来,回应在终端机上。

实作

以美金为例。https://www.google.com/search?q=美金

我们先来用开发工具观察一下需求的元素,有哪些标签方便我们爬取。

可以观察到,我们需求的 span 元素(汇率数值)有着 class DFlfde SwHCTb ,我们能简单写个 requests.get 并搭配 BeautifulSoup 确认是否能够正确定位到该元素。

import requests
from bs4 import BeautifulSoup

url = 'https://www.google.com/search?q=%E7%BE%8E%E9%87%91'
resp = requests.get(url)

soup = BeautifulSoup(resp.text, 'html5lib')
ele = soup.find('span', class_='DFlfde SwHCTb')

print(ele)

找不到该元素(None),我们能直接检视 soup 会发现到与我们在网页上看的不一样。直觉地,我们能将在 chrome 上的 user-agent 放入爬虫的 requests header,再次看是否能够找到该元素。

import requests
from bs4 import BeautifulSoup

url = 'https://www.google.com/search?q=%E7%BE%8E%E9%87%91'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'
resp = requests.get(url, headers={
    'user-agent': user_agent
})

soup = BeautifulSoup(resp.text, 'html5lib')
ele = soup.find('span', class_='DFlfde SwHCTb')

print(ele)

'''
<span class="DFlfde SwHCTb" data-precision="2" data-value="27.795">27.80</span>
'''

成功爬取,接下来能直接取出该元素的 text。

import requests
from bs4 import BeautifulSoup

url = 'https://www.google.com/search?q=%E7%BE%8E%E9%87%91'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'
resp = requests.get(url, headers={
    'user-agent': user_agent
})

soup = BeautifulSoup(resp.text, 'html5lib')
ele = soup.find('span', class_='DFlfde SwHCTb')

print(f'目前 1 美金为 {ele.text} 新台币')
'''
目前 1 美金为 27.80 新台币
'''

接下来,我们能将美金换为变数,让使用者能够自己输入。

import requests
from bs4 import BeautifulSoup
cointype = input('请输入您想要爬取的币种汇率 : ')
url = f'https://www.google.com/search?q={cointype}'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'
resp = requests.get(url, headers={
    'user-agent': user_agent
})

soup = BeautifulSoup(resp.text, 'html5lib')
ele = soup.find('span', class_='DFlfde SwHCTb')

if ele:
    print(f'目前 1 {cointype}为 {ele.text} 新台币')
else:
    print('目前没有汇率')

结语

今天实作了爬取币种汇率的爬虫,能够让使用者自行输入想要查询的币种。

明日内容

明天会带各位在 python 中操作 excel。


<<:  Day 0x14 - 订单查询 (Part2 : View)

>>:  Day15 PHP函数介绍

前端工程学习日记第15天

#网页排版技巧 Part II使用 ul li 设计产品列表 我的作业pencode ...

[Day-24] R语言 - 分群应用(五) 分群预测 - 取得真实资料集&说明 ( real data from UCI )

您的订阅是我制作影片的动力 订阅点这里~ 资料集下载处 影片程序码 ## 应用五: 分群建模 ###...

Day 17 To Do List - 切版 2

第 17 天! 昨天我们建立了, To Do List 专案 这是我们预期的画面, 昨天做到 今天我...

Leetcode 挑战 Day 16 [231. Power of Two]

231. Power of Two 今天我们一起挑战leetcode第231题Power of Tw...

会计,审计和问责制(Accounting, Auditing, and Accountability)& 用户和实体行为分析(UEBA)

日志是会计的工作成果。可以通过查看或检查(审核)一组相关日志(审核记录)以唯一地将活动跟踪到实体来实...