如何获取JavaScript隐藏的购物车弹窗内价格的有效XPath?
Hey there! Let's work through getting the correct XPath for that hidden price element below the struck-through price in your "See Price in Cart" popup. Here's what you can try:
First, reveal the hidden element to inspect its real DOM structure
Since the element is hidden via JavaScript, you can't rely on the initial DOM view. Open your browser's DevTools:- Trigger the "See Price in Cart" popup to load (even if it's hidden, it might already exist in the DOM).
- Head to the Elements panel, and search for the popup's parent container (look for text like "See Price in Cart" or unique class names tied to the popup).
- If the element is set to
display: noneorvisibility: hidden, edit its style in DevTools to force it visible (changedisplaytoblockorvisibilitytovisible) so you can see its exact structure and attributes.
Avoid dynamic IDs like
product-price-3395_clone
IDs with numbers or "clone" in them are often dynamically generated, so they'll break when the page reloads or product data updates. Instead, use relative, stable attributes for targeting:- Example 1: Target based on the popup container and price-specific class names (adjust to match your actual DOM):
//div[contains(@class, 'price-popup-container')]//span[contains(@class, 'sale-price')] - Example 2: Target as a sibling of the struck-through original price:
//span[contains(@class, 'original-price')]/following-sibling::span[1]
- Example 1: Target based on the popup container and price-specific class names (adjust to match your actual DOM):
Test your XPath in DevTools
Use the search bar in the Elements panel (press Ctrl+F) to paste your XPath and check if it highlights the correct element. You can also debug directly in the Console with:$x("your-xpath-here")This returns an array of matching elements—if it's empty, your XPath isn't targeting the right node.
Handle dynamic loading (if using automation tools like Selenium)
If you're scraping this with Selenium, don't try to grab the element immediately. Use an explicit wait to ensure the popup and price element load fully:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(driver, 10) price_element = wait.until(EC.visibility_of_element_located((By.XPATH, "your-corrected-xpath")))
内容的提问来源于stack exchange,提问作者Olga Bautina

