202_美元收盤匯率

題目說明:

請開啟PYD02.py檔案,依下列題意進行作答,使輸出值符合題意要求。作答完成請另存新檔為PYA02.py再進行評分。

程式所產出的檔案,須輸出與程式同一層資料夾。

設計說明:

請撰寫一程式,爬取read.html,取得「新臺幣對美元銀行間成交之收盤匯率」資料,並將其中日期、NTD/USD兩個欄位的名稱與資料轉存為write.csv (需為UTF-8編碼格式)。

輸入輸出:

輸入說明

爬取網頁

輸出說明

日期、NTD/USD兩個欄位的名稱與資料,輸出至write.csv

輸入輸出範例:

範例輸入_1

範例輸出_1

1637821519178

待編修檔案:

# 載入 csv 模組
import csv
# 自 urllib.request 模組載入 urlopen 函數
from ___ import ___
# 自 bs4 模組載入 BeautifulSoup 函數
from ___ import ___


# 將資料寫入csv檔案,編碼為 utf8
file_name = "___"
f = open(file_name, "w", encoding='___')
# 以 csv 模組的 writer 函數初始化寫檔
w = ___.___(f)

# 爬取的目標網頁
htmlname = "___"
# urlopen 函數讀取 html 檔案
html = urlopen(___)
# 指定 BeautifulSoup 的解析器為 lxml
bsObj = BeautifulSoup(html, "___")

count = 0
# 將其中日期、NTD/USD 兩個欄位的名稱與資料轉存為csv
# 資料位置
for single_tr in bsObj.find("___", {"class": "___"}).findAll("___"):
    if count == 0:
        # 擷取資料位置
        cell = single_tr.findAll("___")
    else:
        # 擷取資料位置
        cell = single_tr.findAll("___")
    F0 = cell[0].text
    F1 = cell[1].text
    data = [[F0, F1]]
    w.writerows(data)
    count = count + 1
f.close()

程式碼_1:

import csv

from urllib.request import urlopen
from bs4 import BeautifulSoup

htmlname = "file:./read.html"

html = urlopen(htmlname)
soup=BeautifulSoup(html,'lxml')

trs=soup.find('table',class_="DataTable2").find_all('tr')

datas=[]

for i,tr in enumerate(trs):   
    if i==0:
        datas.append([ th.text.strip() for th in tr.find_all('th')])                
    else:
        datas.append([ td.text.strip() for td in tr.find_all('td')])   

    
with open('./write.csv','w',newline='',encoding='utf-8') as f:
    csv.writer(f).writerows(datas)

程式碼_2:

import csv
# 自 urllib.request 模組載入 urlopen 函數
from urllib.request import urlopen
# 自 bs4 模組載入 BeautifulSoup 函數
from bs4 import BeautifulSoup


# 爬取的目標網頁
htmlname = "file:./read.html"
# urlopen 函數讀取 html 檔案
html = urlopen(htmlname)
soup=BeautifulSoup(html,'lxml')

trs=soup.find('table',class_="DataTable2").find_all('tr')

datas=[]
for i,tr in enumerate(trs):
    data=[]
    if i==0:
        for th in tr.find_all('th'):         
            data.append(th.text.strip())            
    else:
        for td in tr.find_all('td'):          
            data.append(td.text.strip())
            
    datas.append(data)
            
    # print()
    
with open('./write.csv','w',newline='',encoding='utf-8') as f:
    csv.writer(f).writerows(datas)


 搭 配 學 習 

  • Python 3.x 網頁資料擷取與分析特訓教材風_碁峰

    博客來      誠品

  • TQC+ Python 3.x網頁資料擷取與分析特訓教材_全華

    博客來      誠品

 

​​​​​​​

arrow
arrow

    DING BANG 發表在 痞客邦 留言(0) 人氣()