我正在制作一個 Web 抓取工具,可以抓取 Yahoo Finance 并告訴我當前的股價是多少。
運行程式后我不斷收到這樣的錯誤
IndexError: list index out of range
這是代碼
def parsePrice():
r=requests.get('https://finance.yahoo.com/quote/F?p=F')
soup=bs4.BeautifulSoup(r.text,'xml')
#the next line is the supposed problem
price=soup.find_all('div',{'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})[0].Find('span').text
return price
while True:
print('the current price is: ' str(parsePrice()))
我是 python 的初學者,所以任何幫助將不勝感激:)
uj5u.com熱心網友回復:
怎么了?
注意 總是先看看你的湯 - 這就是真相。內容可能總是與開發工具中的視圖略有不同。
沒有<div>您在湯中搜索的此類課程,這就是結果集為空且無法匹配采摘索引的原因[0]
怎么修?
headers在您的請求中添加一些,以顯示您可能是“瀏覽器”:headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}選擇更具體的元素 - 因為您知道請求中的資料符號,您可以直接選擇它:
soup.select_one('[data-symbol="F"]')['value']
例子
注意 抓取的第一條規則:不要傷害網站!意味著您查詢的數量和頻率不應給網站、服務器帶來負擔。因此,請import time -> time.sleep(60)在您的請求之間添加一些延遲 ( ) 或使用官方 api
import bs4
import requests
headers ={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}
def parsePrice():
r=requests.get('https://finance.yahoo.com/quote/F?p=F', headers=headers)
soup=bs4.BeautifulSoup(r.text,'xml')
price = soup.select_one('[data-symbol="F"]')['value']
return price
while True:
print('the current price is: ' str(parsePrice()))
輸出
the current price is: 20.25
the current price is: 20.25
the current price is: 20.25
the current price is: 20.25
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401200.html
上一篇:如何獲取“隱藏”href的值?
