硒元素点击不按预期工作

selenium element click not working as expected

我试图编写一个自动脚本来使用 selenium 下载一些外汇 USD/CAD 价格历史数据。这些数据可在

https://www.dukascopy.com/swiss/english/marketwatch/historical/

我要下载的数据 select candlestick 选项 1 小时,手动 select点击 'Tick' 按钮和 select 'Hour',这看起来像:

要约方 区域变得可点击。如果我用 selenium 自动化这个过程,代码看起来像:

driver = webdriver.Firefox()
driver.get("https://www.dukascopy.com/swiss/english/marketwatch/historical/")

# wait for the frame to load and switch
wait = WebDriverWait(driver, 20)
iframe = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".mainContentBody iframe")))
driver.switch_to.frame(iframe)

for pair in ["USDCAD"]:
    css_selector = "ul > li[data-group][data-instrument='{}/{}']".format(pair[:3], pair[3:])
    li_item = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, css_selector)))
    li_item.click()

    # Set the two options about candlestick
    candle_unit_menu_ele = driver.find_element_by_id(":i")
    candle_unit_menu_ele.click()

    candle_unit_ele = wait.until(EC.visibility_of_element_located((By.ID, ":3"))
    candle_unit_ele.click()

但是,执行这个脚本后,你会发现USD/CAD按钮是selected,而蜡烛单位没有设置为小时,报价方也没有 部分可用。图片:

我想知道为什么会这样,以及如何获得预期的结果。

非常感谢!

编辑:

点击正确的元素可能有问题。所以在行之后:

candle_unit_ele = wait.until(EC.visibility_of_element_located((By.ID, ":3")))

添加:

candle_unit_ele = driver.find_element_by_xpath("//*[@id=':3']/div")

...单击 ID 为 :3 的 div 的子项 div。

所以这两个步骤现在可以是:

# Set the two options about candlestick
candle_unit_menu_ele = driver.find_element_by_id(":i")
candle_unit_menu_ele.click()

candle_unit_ele_parent = wait.until(EC.visibility_of_element_located((By.ID, ":3")))
candle_unit_ele = candle_unit_ele_parent.find_element_by_xpath("//*[@id=':3']/div")
candle_unit_ele.click()

或:

candle_unit_ele = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id=':3']/div")))
candle_unit_ele.click()

顺便说一句,您在以下行中遇到语法错误:

candle_unit_ele = wait.until(EC.visibility_of_element_located((By.ID, ":3"))

需要右括号:

candle_unit_ele = wait.until(EC.visibility_of_element_located((By.ID, ":3")))

此外,虽然不是错误,但行 for pair in ["USDCAD"]: 是不必要的,因为您实际上并没有循环。只需 pair = "USDCAD" 就足够了,除非您打算遍历其他货币选项。但由于它们是单选按钮,您最终只会选择循环运行的最后一个。

我已经试过了,它对我有用:

   candle_unit_ele = wait.until(EC.visibility_of_element_located((By.ID, ":3"))
   candle_unit_ele.click()

将上面的代码替换为:

   candle_unit_ele = driver.find_element_by_id(":3")
   candle_unit_ele.click()