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)
- 1 回答
- 0 關注
- 174 瀏覽
添加回答
舉報