亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

網絡抓取實時數據

網絡抓取實時數據

qq_笑_17 2024-01-11 16:44:10
我目前正在嘗試從雅虎財經頁面抓取實時股市數據。我用的是bs4。我當前的問題是,每當我運行腳本時,它都無法正確更新以反映股票的當前價格。如果有人對如何改變有任何建議,我們將不勝感激。import requestsfrom bs4 import BeautifulSoupwhile True:    page = requests.get("https://nz.finance.yahoo.com/quote/NZDUSD=X?p=NZDUSD=X")    soup = BeautifulSoup(page.text, "html.parser")    price = soup.find("div", {"class": "My(6px) Pos(r) smartphone_Mt(6px)"}).find("span").text    print(price)
查看完整描述

1 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

單獨使用 BS4 是不可能的


該網站特別使用JavaScript來更新頁面和urlib等。僅解析頁面的html內容而不是Java Script或AJAX內容。PhantomJs 或 Selenium Web 瀏覽器提供了一種更加機械化的瀏覽器,通??梢赃\行支持動態網站的 JavaScript 代碼。嘗試使用這個:)


使用 Selenium 可以這樣做:


? ? from selenium import webdriver? ?#its the library

? ? ? ? import time

? ? ? ? from selenium.webdriver.common.keys import Keys

? ? ? ? from bs4 import BeautifulSoup as soup


? ? ? ? ? ? #it Says that we are going to Use chrome browser

? ? ? ? chrome_options = webdriver.ChromeOptions()

? ? ? ? ? ? #hiding the Chrome Browser

? ? ? ? chrome_options.add_argument("--headless")


? ? #Initiating Chrome with all properties we need (in this case we use no specific properties

? ? ? ? driver = webdriver.Chrome(chrome_options=chrome_options,executable_path='C:/Users/shary/Downloads/chromedriver.exe')

? ? #URL We need to open

? ? ? ? url = 'https://nz.finance.yahoo.com/quote/NZDUSD=X?p=NZDUSD=X'


? ? #Starting Our Browser

? ? ? ? driver = webdriver.Chrome()

? ? #Accessing the url .. this will open the page just as you open in Chrome etc.

? ? ? ? driver.get(url)


? ? ? ? while 1:

? ? #it will get you the html content repeatedly .. So you can get the changing price

? ? ? ? ? ? html = driver.page_source

? ? ? ? ? ? page_soup = soup(html,features="lxml")

? ? ? ? ? ? price = page_soup.find("div", {"class": "D(ib) Mend(20px)"}).text

? ? ? ? ? ? print(price)

? ? ? ? ? ? time.sleep(5)



查看完整回答
反對 回復 2024-01-11
  • 1 回答
  • 0 關注
  • 174 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號