求Flipkart平台Python Selenium自动化脚本:筛选≥6GB RAM白色手机并降序
Flipkart手机筛选自动化脚本(Python Selenium)
完整可运行代码
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # 初始化Chrome浏览器(若未配置ChromeDriver环境变量,可使用webdriver-manager自动安装) # 需先安装:pip install webdriver-manager # from webdriver_manager.chrome import ChromeDriverManager # driver = webdriver.Chrome(ChromeDriverManager().install()) driver = webdriver.Chrome() driver.maximize_window() driver.get("https://www.flipkart.com/") try: # 关闭首页登录弹窗 close_login_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[@class='_2KpZ6l _2doB4z']")) ) close_login_btn.click() except: pass # 进入手机专区 mobile_section = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[text()='Mobiles']")) ) mobile_section.click() # 筛选RAM≥6GB的手机 ram_container = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "//div[text()='RAM']/../following-sibling::div")) ) # 勾选6GB、8GB、12GB等符合条件的选项 ram_options = ram_container.find_elements(By.XPATH, ".//div[contains(text(), '6 GB') or contains(text(), '8 GB') or contains(text(), '12 GB')]") for option in ram_options: if not option.is_selected(): option.click() time.sleep(2) # 等待筛选结果加载 # 筛选白色手机 color_container = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "//div[text()='Color']/../following-sibling::div")) ) white_option = color_container.find_element(By.XPATH, ".//div[text()='White']") if not white_option.is_selected(): white_option.click() time.sleep(2) # 按价格降序排列 sort_trigger = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CLASS_NAME, "_2YxCDZ")) ) sort_trigger.click() high_low_option = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[text()='Price -- High to Low']")) ) high_low_option.click() # 等待最终结果加载完成 time.sleep(5) print("筛选完成,结果已按价格降序排列") finally: input("按回车键关闭浏览器...") driver.quit()
关键说明
- 浏览器驱动配置:确保ChromeDriver版本与本地Chrome浏览器匹配,或使用
webdriver-manager自动管理驱动(代码中已注释相关用法)。 - 元素定位适配:Flipkart页面元素可能会更新,若运行时定位失败,需根据当前页面HTML结构调整XPath或选择器。
- 显式等待:使用
WebDriverWait替代固定sleep,提升脚本稳定性,避免因页面加载慢导致的元素找不到问题。 - 弹窗处理:首页的登录弹窗会干扰后续操作,脚本中加入了弹窗关闭逻辑,若未出现弹窗则跳过。
内容的提问来源于stack exchange,提问作者Ashish Sharma
相关产品推荐
相关产品推荐

