如何使用Selenium在Yahoo Finance上单击按钮

时间:2018-11-29 14:45:50

标签: python selenium selenium-webdriver web-crawler webdriverwait

我试图从雅虎财务发现的财务报告中自动提取“季度”数据,但找不到解决方法。我以为可以在财务页面(https://finance.yahoo.com/quote/AAPL/financials?p=AAPL)上单击“季度按钮”,但是下面的代码不起作用。 (什么都没有发生)请您更正代码吗?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome('c:/chromedriver/chromedriver.exe')
ticker_list = ["AAPL"]

for ticker in ticker_list:

    url = "https://finance.yahoo.com/quote/" + ticker + "/financials?p=" + ticker
    driver.get(url)
    wait = WebDriverWait(driver, 3600)
    wait.until(EC.presence_of_element_located((By.XPATH, '//button[text()="Quarterly"]')))
    driver.find_element_by_xpath('//button[text()="Quarterly"]').click

2 个答案:

答案 0 :(得分:1)

“季度”文本是button元素内span标记的一部分,因此未找到。如果您将XPath更改为//span[text()="Quarterly"],则对我有用

答案 1 :(得分:1)

要点击带有季度文字的元素,您需要诱使 WebDriverWait 使所需的元素可点击,并且您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    options = Options()
    options.add_argument("start-maximized")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    ticker_list = ["AAPL"]
    for ticker in ticker_list:
        url = "https://finance.yahoo.com/quote/{}/financials?p={}".format(ticker, ticker)
        driver.get(url)
        WebDriverWait(driver, 3600).until(EC.element_to_be_clickable((By.XPATH, "//section[@data-test='qsp-financial']//span[text()='Quarterly']"))).click()