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

Python Selenium+ChromeDriver自动输入邮政编码失效问题求助

问题分析与解决办法

你的代码存在三个核心问题:

  • 使用了绝对XPATH定位元素,这种方式极易因页面结构变动失效,可靠性极低
  • 输入邮政编码后未触发搜索提交动作,页面根本没执行查询操作
  • 没有等待搜索结果加载完成,直接抓取了初始页面的内容

下面是修复后的完整代码:

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
from bs4 import BeautifulSoup

options = webdriver.ChromeOptions()
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('--ignore-certificate-errors') 
options.add_argument('--log-level=OFF')
options.headless = True
driver = webdriver.Chrome(options=options)

try:
    driver.get("https://www.groceryoutlet.com/store-locator")
    
    # 用更稳定的相对定位找到邮编输入框(替换原绝对XPATH)
    zip_input = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, "zipcode"))
    )
    zip_input.send_keys("90210")
    
    # 触发搜索:按回车键(也可以定位搜索按钮点击)
    zip_input.send_keys(Keys.ENTER)
    
    # 等待搜索结果加载完成,比如等待门店列表元素出现
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, ".store-location-item"))
    )
    
    # 抓取并处理页面内容
    html = driver.page_source
    htmltext = BeautifulSoup(html, "lxml").text
    cleantext = htmltext.replace('\n','').replace('\t','').replace(',','\n')
    print(cleantext)
finally:
    driver.quit()

关键改动说明

  • 用WebDriverWait等待元素加载,避免页面未就绪就执行操作
  • 替换绝对XPATH为By.NAME定位输入框,适配页面结构变动的能力更强
  • 输入邮编后发送Keys.ENTER触发搜索,让页面执行查询逻辑
  • 等待搜索结果的核心元素出现后再抓取页面,确保拿到的是结果页内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:35:10