ChromeDriver中JavaScript与AJAX下拉菜单加载问题求助
问题:Selenium ChromeDriver无法触发AJAX加载下拉菜单选项
我使用Selenium 4.8.3版本,尝试在网页https://eservices.tn.gov.in/eservicesnew/land/areg.html操作地区下拉菜单。普通Chrome浏览器中能正常选择地区并加载后续选项,但ChromeDriver环境下,选择地区后未触发AJAX调用,无法获取后续下拉菜单的选项值。已添加以下参数仍未解决:
--disable-blink-features=AutomationControlledjavascript.enabled=True
原代码如下:
options = webdriver.ChromeOptions() options.add_argument('--disable-blink-features=AutomationControlled') options.add_argument('javascript.enabled=True') DRIVER_PATH = r"C:\Users\user\Downloads\chromedriver_win32\chromedriver.exe" driver = webdriver.Chrome(options=options,executable_path=DRIVER_PATH) driver.get("https://eservices.tn.gov.in/eservicesnew/land/areg.html") abc = driver.find_element('xpath','//*[@id="districtCode"]') all_options = abc.find_elements(By.TAG_NAME,"option") for option in all_options: print(option.text) print("Value is: %s" % option.get_attribute("value")) option.click()
解决方案
使用Selenium原生Select类操作下拉菜单
直接点击option元素可能无法触发页面绑定的AJAX事件,改用Selenium提供的Select类,能更精准触发下拉控件的选择事件。添加显式等待确保AJAX加载完成
AJAX请求需要时间返回数据,必须等待目标元素加载就绪后再操作,避免因元素未渲染导致的异常。补充模拟真实浏览器的配置
增加更多贴近真实用户的浏览器参数,降低被页面识别为自动化工具的概率:
--start-maximized:最大化浏览器窗口--disable-extensions:禁用浏览器扩展- 自定义
user-agent:使用真实Chrome浏览器的UA字符串
修正后的代码
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC options = webdriver.ChromeOptions() options.add_argument('--disable-blink-features=AutomationControlled') options.add_argument('--start-maximized') options.add_argument('--disable-extensions') # 替换为你当前Chrome浏览器的真实User-Agent options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') DRIVER_PATH = r"C:\Users\user\Downloads\chromedriver_win32\chromedriver.exe" driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH) driver.get("https://eservices.tn.gov.in/eservicesnew/land/areg.html") # 等待地区下拉菜单加载完成 district_select = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "districtCode")) ) # 使用Select类操作下拉控件 select = Select(district_select) # 跳过第一个默认空选项,遍历所有可选择的地区 for index in range(1, len(select.options)): option = select.options[index] print(f"地区名称: {option.text}, 值: {option.get_attribute('value')}") # 通过索引选择地区,触发AJAX事件 select.select_by_index(index) # 等待Taluk下拉菜单加载完成 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "talukCode")) ) # 验证Taluk选项是否加载成功 taluk_select = Select(driver.find_element(By.ID, "talukCode")) print(f"当前地区对应的Taluk选项数量: {len(taluk_select.options)}\n")
内容的提问来源于stack exchange,提问作者Madusudhanan
相关产品推荐
相关产品推荐

