首页 > 解决方案 > 无法将 Colab 的输出存储到 Excel 中

问题描述

我编写了下面的代码,但无法将其保存到 Excel 中。

!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
lists = ["FBRX", "GNLN", "TISI"]

for list in lists:
  url = "https://finance.yahoo.com/quote/{list}?p={list}"
  wd.get(url.format(list=list))
  EPS = wd.find_element_by_xpath('//*[@id="quote-summary"]/div[2]/table/tbody/tr[4]/td[2]/span').text
  AV = wd.find_element_by_xpath('//*[@id="quote-summary"]/div[1]/table/tbody/tr[8]/td[2]/span').text
  OYT = wd.find_element_by_xpath('//*[@id="quote-summary"]/div[2]/table/tbody/tr[8]/td[2]/span').text
  print(list,EPS,AV,OYT)

它将输出下表。但在那之后,我不能把下面的东西变成Excel。我尝试了很多方法,但仍然失败。我怎样才能解决这个问题?

FBRX -1.6060 2,031,998 3.25
GNLN -1.0530 827,585 5.40
TISI -2.4640 545,536 10.00

标签: pythonexcelpandasdataframegoogle-colaboratory

解决方案


在 for 循环中构建结果列表,使用 Pandas 制作数据框,然后创建电子表格。

lists = ["FBRX", "GNLN", "TISI"]
result=[]  # empty list to start
for list in lists:
  url = f"https://finance.yahoo.com/quote/{list}?p={list}" # use an f string to format
  wd.get(url.format(list=list))
  EPS = wd.find_element_by_xpath('//*[@id="quote-summary"]/div[2]/table/tbody/tr[4]/td[2]/span').text
  AV = wd.find_element_by_xpath('//*[@id="quote-summary"]/div[1]/table/tbody/tr[8]/td[2]/span').text
  OYT = wd.find_element_by_xpath('//*[@id="quote-summary"]/div[2]/table/tbody/tr[8]/td[2]/span').text
  print(list,EPS,AV,OYT)
  result.append([list,EPS,AV,OYT])   # add the row to the results

result

#[['FBRX', '-1.6060', '2,031,998', '3.25'],
# ['GNLN', '-1.0530', '827,585', '5.40'],
# ['TISI', '-2.4640', '545,536', '10.00']]

import pandas as pd
df = pd.DataFrame(result, columns=['List','EPS','AV','OYT'])
df.to_excel('result.xlsx')

请注意,我必须使 url 生成使用 f 字符串来获取正确的 url。


推荐阅读