美联航自动值机脚本问题:无法定位Continue按钮
如何定位美联航值机页面的动态Continue按钮?
针对你遇到的动态class按钮定位问题,这里有几个简单可靠的方法,结合你的现有代码修改即可:
方法一:通过按钮文本+type属性定位
按钮的type="submit"和显示文本Continue是固定不变的,直接用这个组合定位最稳妥:
首先需要导入显式等待的模块(比implicitly_wait更稳定,适合动态加载的页面),然后修改代码如下:
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By browser = webdriver.Chrome('/Users/jeff/chromedriver/chromedriver') browser.get('https://www.united.com/en/us/checkin') # 输入确认号和姓氏 browser.find_element('name', 'confirmationNumberModel.number').send_keys('AAAA1') browser.find_element('name', 'confirmationNumberModel.lastName').send_keys('LastName') # 显式等待按钮加载完成,最多等10秒 continue_button = WebDriverWait(browser, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[@type='submit' and text()='Continue']")) ) # 点击按钮 continue_button.click()
如果按钮文本前后有空格,也可以用contains(text(), 'Continue')替代text()='Continue',XPath改成://button[@type='submit' and contains(text(), 'Continue')]
方法二:利用class的固定前缀定位
按钮的class虽然有动态哈希后缀,但前面的app-components-Button-styles__button是固定的,结合type="submit"可以这样写:
用CSS选择器的写法:
# 替换上面的等待部分 continue_button = WebDriverWait(browser, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit'][class*='app-components-Button-styles__button']")) ) continue_button.click()
或者XPath写法:
continue_button = WebDriverWait(browser, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'app-components-Button-styles__button') and @type='submit']")) ) continue_button.click()
为什么不用implicitly_wait?
implicitly_wait是全局等待,只会等待元素出现,但不会确保元素可点击。显式等待可以指定等待条件(比如元素可点击),更适合处理动态页面的按钮点击问题,避免出现元素存在但不可点击的报错。
内容的提问来源于stack exchange,提问作者jtg
相关产品推荐
相关产品推荐

