代码之家  ›  专栏  ›  技术社区  ›  Spencer Trinh

使用selenium控制单击哪个条形图,highcharts中的rect节点

  •  0
  • Spencer Trinh  · 技术社区  · 7 年前

    我正在努力编程selenium来点击一个条形图(highcharts)来打开一个新的选项卡。似乎我的xpath不正确。我用过这个网站: freeformatter-XML return hoverChart 它给了我一张空名单。

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.action_chains import ActionChains
    
    driver = webdriver.Firefox()
    driver.get("www.website.com")
    chart_element = driver.find_element_by_xpath(
            "//*[name()='g' and @class='highcharts-series-group']")
    hoverChart_element = driver.find_elements_by_xpath("//*[name()='g' and @data-z-index='0.1']//rect[2]") #try to click on the second rect node
    ActionChains(driver).move_to_element(chart_element).click(hoverChart_element).perform()
    

    为highcharts创建一个通用的xpath是可行的(会打开一个新的选项卡),但是我不能在barplot上迭代地单击下面的每个条。这样只会打开拳头,我无法控制打开哪个条形图。

    chart_element = driver.find_element_by_xpath(
                "//*[name()='g' and @class='highcharts-series-group']//*[name()='rect']")
    ActionChains(driver).click(chart_element).perform()
    

    image of source

    1 回复  |  直到 7 年前
        1
  •  0
  •   Andersson    7 年前

    如果需要单击每个 rect

    main_tab = driver.current_window_handle
    
    for rect in driver.find_elements_by_xpath("//*[name()='g' and @class='highcharts-series-group']//*[name()='rect']"):
        ActionChains(driver).click(rect).perform()
        print('Checking rectangle with (X={}, Y={}) coordinates'.format(rect.get_attribute('x'), rect.get_attribute('y')))
        driver.switch_to.window([tab for tab in driver.window_handles if tab != main_tab][0])
        # Do something on new tab
        driver.close()
        driver.switch_to.window(main_tab)