簡體   English   中英

如何修復我的 python Yahoo Finance Webscrapper 中的類型錯誤、解析和所有其他錯誤

[英]How do I fix TypeError, Parsing, and all other errors in my python Yahoo Finance Webscrapper

如何修復我的 python Yahoo Finance Webscraper 中的類型錯誤、解析和所有其他錯誤。 我無法從 Yahoo Finance 獲取代碼。 任何修復? 看起來 span 類是問題所在,因為它們已被刪除並被 fin-streamer 取代。

錯誤:錯誤

代碼:

import requests
from bs4 import BeautifulSoup
    
    def create_url():
        symbol = str(input('Enter Stock Symbol: '))
        url = f'https://finance.yahoo.com/quote/{symbol}'
        return url
    
    def get_html(url):
        header = {"User Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'}
        response = requests.get(url, headers = header)
    
        if response.status_code == 200:
            return response.text
        else:
            return None
    
    
    def parse_data(html):
    
        soup = BeautifulSoup(html,'html.parser')
        name = soup.find('h1', {'class': 'D(ib) Fz(18px)'}).text
        price = soup.find('fin-streamer', {'class': 'D(ib) Mend(20px)'}).find_all('fin-streamer')[0].text
        change = soup.find('fin-streamer', {'class': 'D(ib) Mend(20px)'}).find_all('fin-streamer')[1].text
        previous_close = soup.find('fin-streamer', {'class': 'Trsdu(0.3s)'}).text
        open_price = soup.find('td',{'class':'Ta(end) Fw(600) Lh(14px)'}).text
        print(f'|Stock Name: {name}|', f'|Stock Price: ${price}|', f'|Change: {change}|', f'|Previous Close: ${previous_close}|', f'|Open Price: ${open_price}|')
        # print(f'Stock Price: ${price}')
        # print(f'Change: {change}')
        # print(f'Previous Close: ${previous_close}')
        # print(f'Open Price: ${open_price}')
        stock_data = {
            'name':name,
            'price':price,
            'change':change ,
            'previous_close': previous_close,
            'open_price': open_price
        }
    
        return stock_data
    
    def main():
        # get users input
        url = create_url()
        # get html
        html = get_html(url)
        # while loop
        i = True
        while i:
            # parse data
            data = parse_data(html)
    
    
    if __name__ == '__main__':
        main()
def create_url():
    symbol = str(input('Enter Stock Symbol: '))
    url = f'https://finance.yahoo.com/quote/%7Bsymbol%7D'
    return url

這個 function 包含一個錯誤:為了將你的symbol插入到url中,你需要做這樣的事情:

url = f'https://finance.yahoo.com/quote/{symbol}'

結果,你得到了錯誤的 URL,但你的 function get_html()如果你未能獲得狀態 200,則返回None將作為None傳遞給 BeautifulSoup,從而生成你的錯誤。

你的get_html() function 檢查狀態很好,但如果狀態指示失敗,它應該失敗。


更新:那是一個復制和粘貼錯誤。

您的錯誤是由於將None傳遞給 BeautifulSoup 引起的 - 您可以通過運行來確認這一點:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(None, 'html.parser')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/private/tmp/venv/lib/python3.9/site-packages/bs4/__init__.py", line 312, in __init__
    elif len(markup) <= 256 and (
TypeError: object of type 'NoneType' has no len()

您正在傳遞None因為那是您的get_html()函數可能返回的內容:

if response.status_code == 200:
  return response.text
else:
  return None

如果您的 function 未能獲得 200 狀態代碼,則您需要失敗,而不是返回None

嘗試用這個替換整個get_html()函數:

def get_html(url):
        header = {"User Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'}
        response = requests.get(url, headers = header)
        response.raise_for_status()
        return response.text

如果 http 請求失敗,此 function 將引發異常 - 否則,它將返回 html,然后您可以將其提供給 BeautifulSoup

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM