Python网页搜罗雅虎-导致空列表

kd3sttzy  于 2023-01-04  发布在  Python
关注(0)|答案(1)|浏览(126)
import requests
import csv
from bs4 import BeautifulSoup

ticker = input('Enter the ticker symbol: ')

url = f'https://finance.yahoo.com/quote/{ticker}/history?p={ticker}'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

table = soup.find('table', {'class': 'W(100%) M(0)'})

rows = table.tbody.find_all('tr')

stock_prices = []
for row in rows:
    cells = row.find_all('td')
    if cells:
        try:
            stock_prices.append(float(cells[4].text.replace(',', '')))
        except ValueError:
            print('Error parsing stock price')

print(stock_prices)

我试图放弃雅虎金融的“市场收盘”价格的一只股票。我通过了html,并不确定我有错误的表格行或单元格。输出列表是空的。
我试图放弃雅虎金融的“市场收盘”价格的一只股票。我通过了html,并不确定我有错误的表格行或单元格。输出列表是空的。

nmpmafwu

nmpmafwu1#

尝试设置User-Agent标题时,请求从雅虎的页面:

import requests
from bs4 import BeautifulSoup

ticker = input("Enter the ticker symbol: ")

url = f"https://finance.yahoo.com/quote/{ticker}/history?p={ticker}"

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0"
}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
table = soup.find("table", {"class": "W(100%) M(0)"})
rows = table.tbody.find_all("tr")

stock_prices = []
for row in rows:
    cells = row.find_all("td")
    if cells and len(cells) > 3:
        try:
            stock_prices.append(float(cells[4].text.replace(",", "")))
        except ValueError:
            print("Error parsing stock price")

print(stock_prices)

图纸(例如AAPL):

Enter the ticker symbol: AAPL
https://finance.yahoo.com/quote/AAPL/history?p=AAPL
[124.9, 129.93, 129.61, 126.04, 130.03, 131.86, 132.23, 135.45, 132.3, 132.37, 134.51, 136.5, 143.21, 145.47, 144.49, 142.16, 142.65, 140.94, 142.91, 146.63, 147.81, 148.31, 148.03, 141.17, 144.22, 148.11, 151.07, 150.18, 148.01, 151.29, 150.72, 148.79, 150.04, 148.28, 149.7, 146.87, 134.87, 139.5, 138.92, 138.38, 138.88, 145.03, 150.65, 153.34, 155.74, 144.8, 149.35, 152.34, 149.45, 147.27, 143.39, 143.86, 143.75, 142.41, 138.38, 142.99, 138.34, 138.98, 140.42, 140.09, 145.43, 146.4, 146.1, 142.45, 138.2, 142.48, 149.84, 151.76, 150.77, 150.43, 152.74, 153.72, 156.9, 154.48, 150.7, 152.37, 155.31, 153.84, 163.43, 157.37, 154.46, 155.96, 154.53, 155.81, 157.96, 157.22, 158.91, 161.38, 163.62, 170.03, 167.53, 167.23, 167.57, 171.52, 174.15, 174.55, 173.03, 173.19, 172.1]

相关问题