Python Selenium操作PHP网站登录后无法定位按钮元素怎么解决
我需要编写脚本实现某PHP搭建网站上的操作自动化,使用Python的Selenium库实现。
首先实例化浏览器,通过xpath定位元素完成登录,代码如下:
browser = webdriver.Chrome() browser.get('目标网站登录页地址') username = browser.find_element_by_xpath('//*[@id="_utilizador"]') password = browser.find_element_by_xpath('//*[@id="_password"]') username.send_keys(USERNAME) password.send_keys(PASSWORD, Keys.ENTER)
遇到的问题
登录完成后需要点击一个type为"button"的input元素,再次使用xpath定位元素时报错:
product_import = browser.find_element_by_xpath('//*[@id="but_2"]')
抛出的异常信息如下:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="but_2"]"} (Session info: chrome=94.0.4606.71)
已尝试的解决方法
我试过使用完整xpath和id属性定位元素,也打印了登录后的base64页面截图确认页面已完成加载更新。
更新1
查阅其他相关问题后,尝试运行以下代码,但抛出了TimeoutException异常:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//*[@id="imain"]'))) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="but_2"]'))).click()
更新2
后续又尝试了以下代码:
iframe = driver.find_element_by_xpath('/html/body/iframe') driver.switch_to.frame(iframe) product_import = driver.find_element_by_xpath('//*[@id="but_2"]')
代码在product_import行报错,说明已经成功切换到对应iframe,但仍然抛出selenium.common.exceptions.NoSuchElementException异常。
最终解决方案
通过Chromium获取按钮的完整xpath后发现,目标元素被两层frame包裹,因此先依次切换两层frame后再定位元素即可成功,运行代码如下:
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "/html/body/iframe"))) WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "/html/frameset/frameset/frameset[2]/frame[1]"))) import_input = driver.find_element_by_xpath("/html/body/div[3]/div[3]/table/tbody/tr/td[1]/input[2]") import_input.send_keys(Keys.ENTER)
如果目标元素是普通button而非input类型的按钮,也可以使用以下代码点击:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div[3]/table/tbody/tr/td[1]/input[2]"))).click()
内容的提问来源于stack exchange,提问作者Juan Andrade
相关产品推荐
相关产品推荐

