我的代碼如下:
import requests
from bs4 import BeautifulSoup
def investopedia()。
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}.
股票 = 'TSLA'/span>
url = f'https://www.investopedia.com/markets/quote?tvwidgetsymbol={ticker.lower()}'。
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml'/span>)
ip_price = soup.find_all('div', {'class':'tv-symbol-price-quote__value js-symbol-last'})[0] 。 find('span').text
print(ip_price)
投資百科()
我在檢查元素時使用的類(在html中):
< div class="tv-symbol-price-quote__value js-symbol-last"/span>> <span>736. 27</span></div>
"span "中的736.27是我需要的數字
請幫助一個網路搜刮的初學者。
uj5u.com熱心網友回復:
你得到index out of range錯誤,因為你的代碼不能找到你現在正在尋找的任何HTML元素。
您所尋找的資訊被保存在一個iframe中。為了檢索您想要的資料,我們必須切換到那個iframe。一種方法是使用Selenium。
from selenium import webdriver
def investopedia()。
ticker = 'TSLA'/span>
url = f'https://www.investopedia.com/markets/quote?tvwidgetsymbol={ticker.lower()}'。
driver = webdriver.Chrome()
driver.get(url)
time.sleep(5) # 它需要時間來下載網頁。
iframe = driver.find_elements_by_css_selector('.tradingview-widget-container > iframe') [0]
driver.switch_to.frame(iframe)
time.sleep(1)
ip_price = driver.find_elements_by_xpath('.//div[@class="tv-symbol-price-quote__value js-symbol-last"]')[0].get_attribute('innerText').strip()
print(ip_price)
投資百科()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/320257.html
標籤:
