python - 尝试从数组中抓取 Yahoo Finance 时“必须是 str,而不是列表”
问题描述
我正在开始我的 Python 编程学习之旅,因此我遇到了我无法弄清楚原因的基本错误
这个想法是通过数组“股票”并通过网络抓取从雅虎获取当前价格
库存 = 0 GGBR4 1 MRVE3 2 TAEE11 3 MGLU3 4 HAPV3
我的代码:
#Workbook selection + sheet selection + range of stocks from the excel
workbook = gc.open_by_key('1DexwEtIPc2yA94QiWzWGR3ZZWo7YIZc00UX1CTMpdB8')
worksheet = workbook.worksheet('summary')
stocks = worksheet.get('stock_range')
df = pd.DataFrame.from_records(stocks)
for i in range(len(stocks)):
symbol = stocks[i]
url = 'https://finance.yahoo.com/quote/' + symbol + '.SA'
data = requests.get(url)
soup = bs4.BeautifulSoup(data.text, "html.parser")
price = soup.findAll('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text
我收到的错误消息:
TypeError Traceback (most recent call last)
<ipython-input-8-fae00e25d5a8> in <module>()
1 for i in range(len(stocks)):
2 symbol = stocks[i]
----> 3 url = 'https://finance.yahoo.com/quote/' + symbol + '.SA'
4 data = requests.get(url)
5 soup = bs4.BeautifulSoup(data.text, "html.parser")
TypeError: must be str, not list
解决方案
我在您的股票清单中进行了调整,并运行了您的示例,它运行良好:
import requests
import bs4
stocks = ['GGBR4', 'MRVE3', 'TAEE11', 'MGLU3', 'HAPV3']
for i in range(len(stocks)):
symbol = stocks[i]
url = 'https://finance.yahoo.com/quote/' + symbol + '.SA'
data = requests.get(url)
soup = bs4.BeautifulSoup(data.text, "html.parser")
price = soup.findAll('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text
但是,您无需获取索引即可通过列表运行。以下方法更有意义,并且更具可读性:
import requests
import bs4
stocks = ['GGBR4', 'MRVE3', 'TAEE11', 'MGLU3', 'HAPV3']
for symbol in stocks
url = 'https://finance.yahoo.com/quote/' + symbol + '.SA'
data = requests.get(url)
soup = bs4.BeautifulSoup(data.text, "html.parser")
price = soup.findAll('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text
推荐阅读
- keras - Windows 10 - 没有名为“keras”的模块
- tensorflow - 如何获取 URL 以下载 Tensorflow 数据集的 csv 文件?
- matlab - Matlab 错误:输出参数过多
- python - 如何删除列表中的列表?
- python - 带有列表和循环的 Python 计算器
- sql - INSERT、SELECT、UPDATE和DELETE都有6个字母是巧合吗?
- reactjs - 在多组件故事书中使用导入的组件参数未定义
- three.js - 在滚动三个 JS 上移动对象
- firebase - 更新列表
扑火基地 - paperclip - 警告:在 ruby 2.7.2 中使用回形针时,URI.escape 已过时