<p>我的代码将13家公司的最新股票信息附加到csv文件(更新的报价)。引号将添加到文件的底部。我只想复制最新的报价(13行)到一个新的csv文件,这将只为每个股票的最新报价一次。这将允许我只导入到excel文件的最新报价。有什么想法吗?你知道吗</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
import csv
from datetime import datetime
from urllib.request import Request, urlopen
from twilio.rest import Client
import os
import random
# list yahoo finance urls for desired stocks
yahoo_urls = ['https://finance.yahoo.com/quote/%5EDJI?p=^DJI', 'https://finance.yahoo.com/quote/%5ESPX?p=^SPX', 'https://finance.yahoo.com/quote/AAPL?p=AAPL', 'https://finance.yahoo.com/quote/KO/', 'https://finance.yahoo.com/quote/SBUX?p=SBUX', 'https://finance.yahoo.com/quote/DIS?p=DIS', 'https://finance.yahoo.com/quote/BRK-B?p=BRK-B', 'https://finance.yahoo.com/quote/NKE?p=NKE']
# loop for each stock with user-agent
for url in yahoo_urls:
full_access = Request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.672.2 Safari/534.20'})
# query the website and return the html to the variable ‘page’
page = urllib.request.urlopen(full_access)
# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, "html.parser")
# Take out the <div> of name and get its value
name_box = soup.find("h1", "D(ib) Fz(18px)")
name = name_box.text.strip()
print(name)
#get the index price
price_box = soup.find("span", "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")
price = price_box.text.strip()
print(price)
# #Day Change
try:
change_box = soup.find("span", class_="Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($dataGreen)")
change = change_box.text.strip()
print(change)
except AttributeError:
change_box = soup.find("span", class_="Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($dataRed)")
change = change_box.text.strip()
print(change)
# # open a csv file with append, so old data will not be erased
with open("updated_quotes", "a") as csv_file:
writer = csv.writer(csv_file)
writer.writerow([name, price, change, datetime.now()])
</code></pre>