如何获取结尾不同的XPATH元素?Selenium添加购物车报错解决
问题解决:Selenium hover商品并添加购物车报错修复
错误原因
你代码里的核心问题有两个:
- 循环写法错误:
for x in str(len(sosete))是把商品数量转成字符串后遍历每个字符,完全没遍历商品元素列表。 - 传递给
move_to_element的是整个元素列表sosete,而不是单个商品WebElement,这直接触发了AttributeError。
修复后的完整代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys import time options = webdriver.ChromeOptions() options.add_experimental_option("detach", True) options.add_argument("start-maximized") webdriver_service = Service('C:\\webdrivers\\chromedriver.exe') driver = webdriver.Chrome(options=options, service=webdriver_service) wait = WebDriverWait(driver, 30) driver.get("https://www.bershka.com/ro/femeie/accesorii/%C8%99osete-c1010194004.html") # 处理Cookie和地区选择 wait.until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler"))).click() wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#geoblocking > div > div > div.select-country-container > button.button.is-sm.confirm"))).click() # 滚动加载更多商品(可选,根据实际需要调整次数) pbody = wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body'))) for x in range(5): pbody.send_keys(Keys.PAGE_DOWN) print('scrolled') time.sleep(1) # 获取所有商品元素 sosete = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="category-product-card"]'))) print(f"找到{len(sosete)}个商品") # 遍历每个商品,hover后添加到购物车 actions = ActionChains(driver) for item in sosete: try: # 先滚动到商品位置,确保元素在视口内 driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", item) time.sleep(0.5) # hover商品 actions.move_to_element(item).perform() # 等待并点击添加购物车按钮 add_cart_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".quick-purchase__detail__button"))) add_cart_btn.click() print("商品已添加到购物车") time.sleep(1) # 给页面反应时间,避免连续操作出错 except Exception as e: print(f"处理商品时出错: {str(e)}") continue
关键修复点说明
- 正确遍历商品列表:用
for item in sosete直接遍历每个商品WebElement,不再操作字符串或列表本身。 - 确保元素在视口内:添加
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", item),避免因为商品在屏幕外导致hover无效。 - 复用ActionChains实例:提前创建
actions = ActionChains(driver),避免每次循环重复创建,提升效率。 - 异常捕获:添加try-except块,单个商品处理失败时不中断整个流程,方便排查问题。
补充说明
不需要纠结商品的XPATH索引,你之前用的//div[@class="category-product-card"]已经能正确定位所有商品元素,这是更稳定的定位方式(比依赖li索引的绝对XPATH可靠得多,页面结构变化时不容易失效)。
内容的提问来源于stack exchange,提问作者user20468552
相关产品推荐
相关产品推荐

