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

Python Unittest中选择首个元素时出现TimeoutException问题求助

问题分析与解决方案

错误原因

你的代码在定位首个搜索结果时触发TimeoutException,核心原因是原XPATH使用的listing-link类已不符合当前Etsy页面的元素结构,导致WebDriver无法找到目标元素。此外,未处理首页可能出现的Cookie弹窗,也可能干扰后续元素定位。

修复步骤与代码修改

1. 处理Cookie弹窗

Etsy首页加载后通常会弹出Cookie授权窗口,需先关闭它,避免遮挡或干扰其他元素操作。

2. 更换搜索结果的定位方式

改用更稳定的CSS选择器或XPATH定位首个商品链接,当前Etsy搜索结果卡片的类为v2-listing-card,可通过这个父元素定位内部链接。

3. 优化等待条件

对需要点击的元素,使用element_to_be_clickable代替visibility_of_element_located,确保元素不仅可见还可交互。

4. 更可靠的购物车验证

直接定位购物车的计数元素,而非检查page_source,结果更准确。


修改后的完整代码:

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class EtsyTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.wait = WebDriverWait(self.driver, 15)  # 延长等待时间,适配页面加载
        
    def tearDown(self):
        self.driver.quit()
        
    def test_add_to_cart_etsy(self):
        self.driver.get("https://www.etsy.com/")
        
        # 处理Cookie弹窗(若存在)
        try:
            accept_cookie_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Accept')]")))
            accept_cookie_btn.click()
        except:
            # 若弹窗未出现,跳过
            pass
        
        # 执行搜索
        search_field = self.wait.until(EC.element_to_be_clickable((By.ID, "global-enhancements-search-query")))
        search_field.send_keys("handmade jewelry")
        search_field.send_keys(Keys.RETURN)
        
        # 定位并点击首个搜索结果
        first_item = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.v2-listing-card__info a")))
        first_item.click()
        
        # 切换到新打开的商品页面(因为点击商品会打开新标签)
        self.driver.switch_to.window(self.driver.window_handles[1])
        
        # 点击加入购物车按钮
        add_to_cart_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@data-add-to-cart-button]")))
        add_to_cart_btn.click()
        
        # 验证购物车数量
        cart_count = self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span[data-cart-count]")))
        self.assertEqual(cart_count.text, "1")

if __name__ == "__main__":
    unittest.main()

关键修改说明

  • 新增Cookie弹窗处理逻辑,避免弹窗干扰操作
  • 改用div.v2-listing-card__info a CSS选择器定位首个商品链接,适配当前页面结构
  • 处理商品页面打开新标签的情况,切换到新窗口后再操作
  • 更换加入购物车按钮的定位XPATH为//button[@data-add-to-cart-button],更稳定
  • 通过定位购物车计数元素span[data-cart-count]直接验证数量,比检查页面源码更可靠

内容的提问来源于stack exchange,提问作者GoT GOt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:34:57