Selenium如何定位Shopee站点悬停运费后显示的配送日期元素
问题原因排查&解决方法
- 现有代码存在几个核心问题导致定位失败:
- 基础语法错误:
url未加字符串引号,也未导入time、pandas依赖包 - 悬停目标选择错误:你定位的
shopee-drawer是悬停后才会弹出的容器,不是可触发悬浮的运费区域本身,元素定位逻辑颠倒 - 未处理Shopee默认弹窗:首次打开页面会弹出地区选择/Cookie提示,遮挡页面元素导致悬停动作无法生效
- 未绕过反爬检测:Shopee会识别Selenium的自动化特征,拦截脚本的交互操作
- 基础语法错误:
- 修正后的可用代码如下:
import time import pandas as pd from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, TimeoutException from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # 配置Chrome,禁用自动化特征绕过反爬 chrome_options = Options() chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option("useAutomationExtension", False) chrome_options.add_argument("--disable-blink-features=AutomationControlled") chromedriver = "path to chromedriver" # 替换为你的chromedriver实际路径 driver = webdriver.Chrome(chromedriver, options=chrome_options) driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})" }) url = "https://shopee.sg/-Bundle-of-2-SOMEBYMI-150ml-AHA-BHA-PHA-30days-Miracle-Toner-150ml-i.93906301.7143079648?ads_keyword=wkdaelpmissisiht&adsid=3545314&campaignid=1926059&position=0" driver.get(url) time.sleep(3) # 先关闭首页弹窗(如果存在) try: close_btn = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, '//div[@class="shopee-popup__close-btn"]'))) close_btn.click() time.sleep(1) except: pass delivery_date = None try: # 定位正确的可悬停运费触发区域 shipping_trigger = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//div[contains(text(),"Shipping Fee")]/parent::div'))) # 悬停时加小延迟保证动作正常触发 ActionChains(driver).move_to_element(shipping_trigger).pause(1).perform() # 等待配送日期元素加载 delivery_date = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="sYwpBA"]'))) except (NoSuchElementException, StaleElementReferenceException, TimeoutException): delivery_date = None row = {} if delivery_date is not None: row['Delivery Date'] = delivery_date.text.strip() else: row['Delivery Date'] = "" # 修正原代码变量名错误,单条数据用[row]不是rows df = pd.DataFrame([row]) df.to_csv('delivery_date.csv', index=False) driver.quit()
- 补充说明:Shopee的前端类名会不定期更新,如果后续
sYwpBA定位失效,重新冻结调试获取最新的类名替换即可。
内容的提问来源于stack exchange,提问作者dwk963
相关产品推荐
相关产品推荐

