Selenium爬取成绩登录问题:提交后跳转至hangup.php3页面
解决思路
1. 修正表单提交方式
不要直接调用输入框的submit()方法,找到页面上的登录按钮,用click()触发提交。很多校园门户的登录逻辑绑定在按钮的点击事件上,直接提交输入框可能跳过必要的JS验证或会话初始化步骤。
示例修改代码:
# 先定位登录按钮(需根据页面实际元素调整,比如用XPath匹配提交按钮) login_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[@type='submit']")) ) login_btn.click()
2. 规避Selenium反爬检测
校园门户通常会检测自动化工具,可通过以下方式伪装成真实浏览器:
- 添加Chrome参数隐藏自动化特征:
from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--disable-blink-features=AutomationControlled') options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36') driver = webdriver.Chrome(service=service, options=options) - 替换固定
time.sleep()为WebDriverWait,按元素加载状态等待,既稳定又减少机械操作痕迹:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def login(): driver.maximize_window() driver.get("https://portal.afeka.ac.il/desktop") # 等待用户名输入框加载完成 username = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.NAME, "username")) ) username.send_keys("你的用户名") password = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.NAME, "password")) ) password.send_keys("你的密码") # 等待登录按钮可点击后触发点击 login_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[@type='submit']")) ) login_btn.click()
3. 检查会话Cookie完整性
首次访问门户时,网站会设置必要的会话Cookie,直接提交表单可能因缺少Cookie被拦截。可在driver.get()后等待2-3秒,让Cookie完全加载,或通过print(driver.get_cookies())查看是否有核心会话Cookie存在。
4. 模拟人类操作细节
加入更贴近真实用户的操作,比如点击输入框后再输入、输入时添加短暂停顿:
username.click() time.sleep(0.3) username.send_keys("你的用户名") password.click() time.sleep(0.3) password.send_keys("你的密码")
5. 排查跳转后的页面信息
在跳转到hangup.php3页面时,暂停脚本并打印页面源码,查看是否有明确错误提示(如账号密码错误、需验证码、会话超时等):
time.sleep(3) print(driver.page_source)
内容的提问来源于stack exchange,提问作者UnknownLizard
相关产品推荐
相关产品推荐

