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

Selenium操作99acres页面重定向失败:无法加载页面问题求助

问题分析与解决方案

核心问题排查

页面加载失败大概率由以下原因导致:

  • 硬等待(time.sleep)无法精准匹配页面加载状态,导致交互时机错误
  • 点击搜索建议后重复触发回车操作,引发重复请求或页面状态混乱
  • Selenium默认特征被网站反爬机制识别,限制了页面访问

具体修复方案

1. 替换硬等待为显式等待

显式等待能根据元素状态动态等待,比固定时长的time.sleep更可靠,避免过早或过晚执行操作:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def extractSocietyData(societyName:str)->None:
    # 添加浏览器配置,规避反爬
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")  # 最大化窗口,模拟真实用户
    options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    
    driver = webdriver.Chrome(options=options)
    wait = WebDriverWait(driver, 20)  # 最长等待20秒
    
    driver.get("https://www.99acres.com/")
    
    # 等待页面标题加载完成
    wait.until(EC.title_contains("99acres"))
    print(driver.title)
    
    # 滚动到搜索栏位置(确保元素可见)
    search_bar = wait.until(EC.presence_of_element_located((By.ID, "keyword")))
    driver.execute_script("arguments[0].scrollIntoView();", search_bar)
    
    # 点击搜索栏并输入内容
    search_bar.click()
    search_bar.send_keys(societyName)
    
    # 等待搜索建议框出现并加载完成
    search_suggestions = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#suggestions_custom")))
    first_suggestion = wait.until(EC.element_to_be_clickable((By.TAG_NAME, 'li')))
    first_suggestion.click()
    
    # 等待搜索结果页加载完成(点击建议后网站会自动跳转,无需额外回车)
    wait.until(EC.url_contains("search"))
    
    url = driver.current_url
    print(f"当前URL: {url}")
    
    extract_data(driver.page_source)
    driver.quit()  # 操作完成后关闭驱动

2. 移除重复触发的回车操作

点击搜索建议后,99acres网站会自动发起搜索并跳转结果页,额外的search_bar.send_keys(Keys.RETURN)会导致重复请求,干扰页面正常加载,直接移除该代码即可。

3. 规避反爬检测

通过ChromeOptions添加配置,隐藏Selenium的自动化特征,模拟真实用户的浏览器环境:

  • --start-maximized:最大化窗口,避免小窗口被识别为爬虫
  • 自定义user-agent:匹配当前Chrome版本的UA字符串
  • 禁用自动化提示开关:防止网站检测到Selenium的存在

额外排查点

  • 确保ChromeDriver版本与本地Chrome浏览器主版本号完全一致
  • 尝试禁用浏览器扩展,避免扩展干扰页面加载
  • 若仍有问题,可添加options.add_argument("--disable-blink-features=AutomationControlled")进一步隐藏自动化特征

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:31:11