Python Selenium检测元素title变化并返回布尔值求助
课程剩余座位监控Selenium解决方案
需求说明
用Python Selenium检测指定页面元素,当元素的title属性变为“ 1 of 20 seats remain.”时返回True,通过循环刷新页面监控课程退课情况,以便及时选课。
目标HTML元素:
<td data-id="329083" data-property="status" xe-field="status" class="readonly" data-content="Status" style="width: 8%; display: none;" title=" FULL: 0 of 20 seats remain."> <div class="status-full"> <span class="status-bold ">FULL</span>: 0 of 20 seats remain. </div> </td>
错误方法分析
方法1错误点
代码:
status = driver.find_element(By.XPATH,"/html/body/main/div[3]/div/div[2]/div/div[1]/div/div[2]/div[3]/div[2]/div[1]/div[1]/div[1]/div/table/tbody/tr/td[11]").text status.get_attribute(" FULL: 0 of 20 seats remain.") if status == "FULL:0of20seatsremain.": print("Seats Not Avaliable") else: print("Error")
报错:
Exception has occurred: AttributeError 'str' object has no attribute 'get_attribute' status.get_attribute(" FULL: 0 of 20 seats remain.")
问题:.text会把元素文本转成字符串,status变成字符串后就没有get_attribute方法了;而且get_attribute的参数应该是属性名(比如"title"),不是属性值。
方法2错误点
代码:
title = " FULL: 0 of 20 seats remain." courseStat = driver.find_element(By.CSS_SELECTOR("[title^='" + title + "']")).text
报错:
Exception has occurred: TypeError 'str' object is not callable courseStat = driver.find_element(By.CSS_SELECTOR("[title^='" + title + "']")).text
问题:By.CSS_SELECTOR是字符串常量,不是函数,正确写法是把它作为第一个参数,选择器字符串作为第二个参数。
正确实现代码
核心思路
- 用稳定属性定位元素(比如
data-id+data-property,别用容易失效的绝对XPATH) - 获取元素的
title属性值 - 判断值是否匹配目标字符串
- 循环刷新页面,直到检测到可用座位
完整代码
from selenium import webdriver from selenium.webdriver.common.by import By import time def check_seat_availability(driver): try: # 用data-id和data-property组合定位,稳定性更高 status_element = driver.find_element(By.CSS_SELECTOR, "td[data-id='329083'][data-property='status']") title_attr = status_element.get_attribute("title") # 注意目标字符串开头的空格,要完全匹配 return title_attr == " 1 of 20 seats remain." except: # 页面加载异常或元素找不到时返回False return False # 初始化浏览器 driver = webdriver.Chrome() driver.get("你的大学选课页面地址") # 这里补充你的登录操作(输入账号、密码等) # ... # 循环监控 while True: if check_seat_availability(driver): print("有剩余座位!赶紧选课!") break print("暂无座位,30秒后刷新...") time.sleep(30) # 设置合理间隔,避免被网站限制 driver.refresh() # 后续选课逻辑自行补充 # ... driver.quit()
注意事项
- 定位元素优先用
data-id、class等不易变动的属性,绝对XPATH一旦页面结构改了就会失效 get_attribute("title")才是获取元素title属性的正确方式- 加入异常捕获能避免页面加载慢导致的程序崩溃
- 刷新间隔别太短,防止被网站判定为恶意请求
内容的提问来源于stack exchange,提问作者Juma Alshamsi
相关产品推荐
相关产品推荐

