使用Selenium Python无法点击复选框且无法处理图片验证求助
问题复现
我想要点击页面上的复选框,但现有代码无法正常运行,计划执行的操作步骤如下:
- 打开目标网站
- 选择职业,示例:Dental(牙科)
- 选择执照类型,示例:Dentist(牙医)
- 输入带*的字母以获取全部对应记录
- 点击复选框
- 点击搜索按钮
此外脚本运行时还会触发图片验证流程,暂时无法处理该环节。
现有问题分析
- 复选框点击失败:你使用了绝对路径
/html/body/div[1]定位复选框,该路径指向页面根节点下的第一个div,和实际的复选框元素完全不匹配,自然无法触发点击 - 验证码触发:该网站使用了反爬检测机制,常规Selenium启动的Chrome会被识别为自动化程序,因此会弹出验证码拦截
修复后代码
home_page = 'https://forms.nh.gov/licenseverification/' import datetime import time from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options # 原启动方式增加反检测参数,降低被识别概率 chrome_options = Options() chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option("useAutomationExtension", False) driver = webdriver.Chrome(r"C:\Users\psingh\AppData\Local\Programs\Python\Python38-32\chromedriver.exe", options=chrome_options) # 抹除浏览器自动化特征 driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})" }) driver.get(home_page) select_prof = WebDriverWait(driver, 30).until( EC.presence_of_element_located((By.ID, "t_web_lookup__profession_name"))) Select(select_prof).select_by_value('Dental') select_lic_type = WebDriverWait(driver, 30).until( EC.presence_of_element_located((By.ID, "t_web_lookup__license_type_name"))) Select(select_lic_type).select_by_value('Dentist') time.sleep(1) send = WebDriverWait(driver, 30).until( EC.presence_of_element_located((By.ID, "t_web_lookup__last_name")) ) send.send_keys('A*') time.sleep(1) # 修复复选框定位:使用正确的元素ID+显式等待 agree_checkbox = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "t_web_lookup__cb_agree")) ) agree_checkbox.click() # 调试阶段可打开下方注释,预留30秒手动完成验证码操作 # time.sleep(30) # 点击搜索按钮 search_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "sch_button")) ) search_btn.click() # 等待结果加载 time.sleep(3)
验证码处理补充说明
- 调试阶段直接开启代码中的30秒等待,手动完成验证后脚本会自动继续运行
- 批量运行场景可以对接第三方打码服务自动处理验证码
- 替换为undetected-chromedriver启动浏览器,可以大幅降低被检测概率,减少验证码弹出频次
内容的提问来源于stack exchange,提问作者Pushpendra Singh
相关产品推荐
相关产品推荐

