You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Selenium统计页面graphs数、获取tooltips并自动化下拉单选交互?

Solution for Your Selenium Python Task

Hey there! Let's walk through how to solve both parts of your problem using Python and Selenium. I'll break it down into clear, actionable steps with code examples you can adapt to your specific page.

Part 1: Count Graphs & Extract Their Tooltips

First, we need to locate all the graph elements on your page and retrieve their tooltips. Tooltips often appear when you hover over a graph, so we'll use Selenium's ActionChains to simulate mouse hover. Here's how to do it:

Step-by-Step Code

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

def get_graph_tooltips(driver):
    # Wait for graphs to load (adjust the selector to match your page's graph elements)
    graphs = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.graph-container"))  # Update this selector!
    )
    print(f"Total graphs found: {len(graphs)}")
    
    tooltip_data = []
    for idx, graph in enumerate(graphs):
        # Simulate mouse hover to trigger tooltip
        ActionChains(driver).move_to_element(graph).perform()
        
        # Wait for tooltip to appear (adjust selector to match your tooltip element)
        tooltip = WebDriverWait(driver, 5).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, "div.tooltip"))  # Update this selector!
        )
        tooltip_text = tooltip.text
        tooltip_data.append({"graph_index": idx+1, "tooltip": tooltip_text})
        
        # Optional: Move mouse away to close tooltip for next iteration
        ActionChains(driver).move_to_element(driver.find_element(By.TAG_NAME, "body")).perform()
    
    return tooltip_data

# Initialize driver (use Chrome, Firefox, etc.)
driver = webdriver.Chrome()
driver.get("your_page_url_here")

# Get initial tooltip data
initial_tooltips = get_graph_tooltips(driver)
for item in initial_tooltips:
    print(f"Graph {item['graph_index']} Tooltip: {item['tooltip']}")

Notes:

  • Update Selectors: Replace div.graph-container and div.tooltip with the actual CSS selectors or XPATHs for your page's graphs and tooltips. If your tooltip uses the title attribute instead of a separate element, you can skip the hover and just use graph.get_attribute("title").
  • Wait Strategies: Using WebDriverWait ensures we don't try to interact with elements before they're ready, which avoids errors.

Part 2: Automate Dropdown & Radio Button Interactions

Next, we need to iterate through all possible combinations of dropdown and radio button options, update the page, and collect the corresponding tooltip data. Here's how to handle that:

Step-by-Step Code

from selenium.webdriver.support.ui import Select

def iterate_dropdown_radio(driver):
    # Locate dropdown (adjust selector)
    dropdown = Select(driver.find_element(By.ID, "your_dropdown_id"))  # Update ID/selector
    # Get all dropdown options
    dropdown_options = [option for option in dropdown.options if option.text != ""]  # Skip empty options
    
    # Locate radio buttons (adjust selector)
    radio_buttons = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.NAME, "your_radio_group_name"))  # Update name/selector
    )
    
    # Iterate through all combinations
    for dropdown_option in dropdown_options:
        dropdown.select_by_visible_text(dropdown_option.text)
        print(f"\nSelected Dropdown Option: {dropdown_option.text}")
        
        for radio_btn in radio_buttons:
            radio_btn.click()
            # Wait for page data to update (adjust condition to match your page's load indicator)
            WebDriverWait(driver, 10).until(
                EC.staleness_of(driver.find_element(By.CSS_SELECTOR, "div.graph-container"))  # Wait for graphs to refresh
            )
            print(f"Selected Radio Option: {radio_btn.get_attribute('value')}")
            
            # Get tooltips for current selection
            current_tooltips = get_graph_tooltips(driver)
            # Do something with the data (save to CSV, print, etc.)
            for item in current_tooltips:
                print(f"  Graph {item['graph_index']} Tooltip: {item['tooltip']}")

# Call the function to start interactions
iterate_dropdown_radio(driver)

# Cleanup
driver.quit()

Notes:

  • Dropdown Handling: Use Selenium's Select class for easy interaction with dropdowns. You can also select by index or value instead of visible text.
  • Radio Buttons: Make sure you're targeting all buttons in the same group (usually same name attribute). After clicking, wait for the page to refresh—use staleness_of if the graph elements are replaced, or wait for a specific element to update.
  • Data Storage: Instead of printing, you can save the tooltip data to a CSV file using Python's csv module or to a database for later analysis.

Final Tips

  • Inspect Elements: Use your browser's DevTools (F12) to find the correct selectors for graphs, tooltips, dropdowns, and radio buttons.
  • Handle Dynamic Content: If your page uses AJAX to load data, adjust the wait conditions to ensure elements are fully loaded before interacting.
  • Headless Mode: For faster execution, you can run the browser in headless mode (e.g., options.add_argument("--headless=new") for Chrome).

内容的提问来源于stack exchange,提问作者sudheer divi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:13:11