问题的根本原因:
语法不正确。请参见下文。
在第二个代码中,将以下行从更改为:
current_price = driver.find_element('div.nre-quick-quote-price').text
收件人:
current_price = driver.find_element(By.CSS_SELECTOR, 'div.nre-quick-quote-price').text
完整工作代码:
注:我添加了
explicitwaits
在您的代码中确保代码更加一致,这样即使网站响应/加载速度有点慢,您的代码也会处理它。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
def stock_price(symbol: str = "AAPL") -> str:
driver = webdriver.Chrome()
url = "https://digital.fidelity.com/prgw/digital/research/quote/dashboard/summary?symbol=" + symbol
driver.get(url)
wait = WebDriverWait(driver, 10)
current_price = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.nre-quick-quote-price'))).text
return current_price
print(stock_price())
结果:
$165.02
Process finished with exit code 0
更新了在无头模式下运行的代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
def stock_price(symbol: str = "AAPL") -> str:
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36")
driver = webdriver.Chrome(options=options)
url = "https://digital.fidelity.com/prgw/digital/research/quote/dashboard/summary?symbol=" + symbol
driver.get(url)
wait = WebDriverWait(driver, 10)
current_price = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.nre-quick-quote-price'))).text
return current_price
print(stock_price())