所以我試圖讓這個腳本從ticker
變量中運行多個變量
例子 ticker = ['NFLX','APPL']
我怎樣才能循環這個腳本,以便我可以在多個變量上運行它
import requests
from bs4 import BeautifulSoup
ticker = 'NFLX'
url = 'https://finance.yahoo.com/quote/' + ticker
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
name = soup.find('div', {'class':'Mt(15px)'}).find_all('h1')[0].text
price = soup.find('div', {'class':'D(ib) Mend(20px)'}).find_all('span')[0].text
change = soup.find('div', {'class':'D(ib) Mend(20px)'}).find_all('span')[1].text
cap = soup.find('div', {'class':'D(ib) W(1/2) Bxz(bb) Pstart(12px) Va(t) ie-7_D(i) ie-7_Pos(a) smartphone_D(b) smartphone_W(100%) smartphone_Pstart(0px) smartphone_BdB smartphone_Bdc($seperatorColor)'}).find_all('span')[0].text
capnumber = soup.find('div', {'class':'D(ib) W(1/2) Bxz(bb) Pstart(12px) Va(t) ie-7_D(i) ie-7_Pos(a) smartphone_D(b) smartphone_W(100%) smartphone_Pstart(0px) smartphone_BdB smartphone_Bdc($seperatorColor)'}).find_all('span')[1].text
topnews = soup.find('h3', {'class':'Mb(5px)'}).find_all('a')[0].text
print(name)
print ('https://finance.yahoo.com/quote/' + ticker)
print("Last Price:",price)
print("Change:", change)
print(cap,":", capnumber)
print("Top News:", topnews)
當前腳本返回
Netflix, Inc. (NFLX)
https://finance.yahoo.com/quote/NFLX
Last Price: 658.29
Change: +4.23 (+0.65%)
Market Cap : 291.591B
Top News: Russia investigates Netflix after complaint over LGBT content
我希望它仍然返回相同的佈局,但然後在每個結果之間間隔或用虛線分隔
我對編碼非常陌生,所以我確定這是獲得所需結果的非常麻煩的途徑,所以如果有人也能提供建議以使其更整潔,那也將不勝感激。
您可以將所有內容放入一個方法中,然後將一個參數“ticker”傳遞給它,一次一個列表中的一個變量。或者,您可以傳入整個列表並在方法內執行 for 循環。
import requests
from bs4 import BeautifulSoup
#given input
tickers = ['NFLX','APPL']
def urlDisplay(ticker):
url = 'https://finance.yahoo.com/quote/' + ticker
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
name = soup.find('div', {'class':'Mt(15px)'}).find_all('h1')[0].text
price = soup.find('div', {'class':'D(ib) Mend(20px)'}).find_all('span')[0].text
change = soup.find('div', {'class':'D(ib) Mend(20px)'}).find_all('span')[1].text
cap = soup.find('div', {'class':'D(ib) W(1/2) Bxz(bb) Pstart(12px) Va(t) ie-7_D(i) ie-7_Pos(a) smartphone_D(b) smartphone_W(100%) smartphone_Pstart(0px) smartphone_BdB smartphone_Bdc($seperatorColor)'}).find_all('span')[0].text
capnumber = soup.find('div', {'class':'D(ib) W(1/2) Bxz(bb) Pstart(12px) Va(t) ie-7_D(i) ie-7_Pos(a) smartphone_D(b) smartphone_W(100%) smartphone_Pstart(0px) smartphone_BdB smartphone_Bdc($seperatorColor)'}).find_all('span')[1].text
topnews = soup.find('h3', {'class':'Mb(5px)'}).find_all('a')[0].text
print(name)
#print('https://finance.yahoo.com/quote/' + ticker)
#can just print url variable straight away since you declared it already above.
print(url)
print("Last Price:",price)
print("Change:", change)
print(cap,":", capnumber)
print("Top News:", topnews)
#driver code
def main():
for i in tickers:
urlDisplay(i)
print('-' * 20)
if __name__ == "__main__":
main()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句