首页 > 解决方案 > Selenium Python - 如何使用 Selenium 从 Yahoo Finance 的历史数据中单击时间段

问题描述

我在试图找到时间段的元素时遇到了麻烦。我要做的下一步是选择最大周期,然后下载数据。我尝试了检查元素,但找不到适合 XPATH 的元素。

这是我的代码

enter code here
import selenium
import time
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "none"   # Do not wait for full page load
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://finance.yahoo.com/quote/XRP-USD?p=XRP-USD")
time.sleep(2.9)
driver.execute_script("window.stop();")
clickHistorical = driver.find_element_by_xpath('//span[text()= "Historical Data"]')
clickHistorical.click()
time.sleep(3.9)
grabTimePeriod = driver.find_element_by_xpath("HOW TO FIND THE ELEMENT OF THE TIME PERIOD??").click()

标签: pythonseleniumselenium-webdriveryahoo-financecryptocurrency

解决方案


grabTimePeriod = driver.find_element_by_xpath("//span[contains(text(),'Time Period')]/../..//div/span")

解释:对我来说最好的方法是在 xpath 的帮助下通过文本找到它,因为在这个元素中使用类名:<span class="C($linkColor) Fz(14px)">Apr 13, 2020 - Apr 13, 2021</span>不稳定。

另外,导入:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By as By

并在单击之前等待此定位器。

wait.until(EC.element_to_be_clickable(
    (By.XPATH, "//span[contains(text(),'Time Period')]/../..//div/span")))

grabTimePeriod = driver.find_element_by_xpath("//span[contains(text(),'Time Period')]/../..//div/span")
grabTimePeriod.click()

推荐阅读