Selenium报Cannot click on element异常无法提交表单问题咨询
Selenium自动化提交表单点击异常问题解决方案
问题描述
使用Python搭配Selenium开展网页自动化操作,批量获取网页查询结果时遇到无法点击链接/按钮提交表单的问题,运行脚本抛出如下异常:selenium.common.exceptions.MoveTargetOutOfBoundsException: Message: Cannot click on element
先后尝试三种提交方案均未生效:
- 执行
driver.find_element_by_xpath('/html/body/div/div/div[4]/center/div/p').submit() - 执行
driver.find_element_by_xpath('/html/body[@class='vsc-initialized']/div[@id='wrap']/div[@id='content']/div[4]/center/div[@id='locationSearch']/p[@id='locationSearchButton']').submit() - 执行
driver.find_element_by_id('locationSearchButton').click()
待解决的两个核心疑问:
- 有什么可行方法可以正常完成表单提交?
- 结果展示区域为textarea元素,是否可以使用find_element_by_xpath方法获取结果内容?
当前使用IE浏览器驱动进行测试,完整代码如下:
# Use IE driver = webdriver.Ie() # Open Link driver.get(r'https://www.freemaptools.com/find-australian-postcodes-inside-radius.htm') time.sleep(3) driver.maximize_window() # Copy Excel content to each line for i in range(2, r + 1): # Clean the input area of form driver.find_element_by_id('tb_radius').clear() driver.find_element_by_id('locationSearchTextBox').clear() # Input Radius driver.find_element_by_id('tb_radius').send_keys(ws.cell(i, 2).value) # Input Search Postcode driver.find_element_by_id('locationSearchTextBox').send_keys(ws.cell(i, 1).value) # Submit driver.find_element_by_id('locationSearchButton').click() # Wait 5 seconds time.sleep(5) # Gain the output postcode result = driver.find_element_by_xpath('/html/body/div[2]/div[2]/center[3]/textarea') ws.cell(i, 3).value = result.text # back excel file if i < r: driver.back() # Save as xlsx file wb.save('c:/Code/MappingAreaPostcode.xlsx')
问题解决方法
表单提交点击异常修复
抛出MoveTargetOutOfBoundsException的核心原因是目标元素不在当前视口可交互范围内,IE驱动对元素坐标计算、页面缩放比例的敏感度远高于Chrome/Edge驱动,加上调用submit()方法仅对form标签内的原生提交按钮生效,当前定位的p标签不属于表单提交元素,自然无法触发提交逻辑。按以下步骤调整即可正常提交:
- 初始化IE驱动时增加配置,规避IE本身的设置带来的坐标偏移问题
from selenium.webdriver.ie.options import Options ie_options = Options() ie_options.ignore_protected_mode_settings = True ie_options.ignore_zoom_level = False ie_options.enable_persistent_hover = True driver = webdriver.Ie(options=ie_options)
- 运行前手动确认IE浏览器页面缩放比例为100%,缩放比例异常会直接导致元素点击坐标计算错误。
- 替换原有直接点击的逻辑,点击前先将元素滚动到视口中间位置,再通过JS触发点击,绕过前端的元素位置校验:
submit_btn = driver.find_element_by_id('locationSearchButton') # 滚动元素到视口中间 driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", submit_btn) time.sleep(0.5) # JS触发点击 driver.execute_script("arguments[0].click();", submit_btn)
- 移除循环内的
driver.back()逻辑,页面回退在IE环境下极易触发DOM缓存失效、元素重新加载的异常,单次查询完成后直接清空输入框内容即可进入下一轮查询,减少不必要的页面跳转。
textarea元素取值说明
textarea元素完全支持通过find_element_by_xpath方法定位,但textarea的展示内容存储在元素的value属性中,直接调用.text无法获取到内容,需要调整取值逻辑,同时建议替换长绝对路径XPath为相对定位,提升定位稳定性:
# 相对路径定位结果输出区textarea result = driver.find_element_by_xpath('//div[@id="output"]/textarea') # 读取value属性获取内容 ws.cell(i, 3).value = result.get_attribute('value')
- 不建议写死
time.sleep(5)等待结果加载,可以增加显式等待判断textarea内容不为空后再取值,避免网络波动时拿到空结果。
内容的提问来源于stack exchange,提问作者JoeL
相关产品推荐
相关产品推荐

