【问题标题】:Cannot locate element using Selenium无法使用 Selenium 定位元素
【发布时间】:2018-06-20 10:31:25
【问题描述】:

我将 Selenium 与 Python 和 Chromedriver 一起使用来单击“按钮”(实际上不是 HTML 中的按钮,但看起来像屏幕上的一个并且是可点击的)。 HTML 在下面,我正在尝试单击带有“button-new”ID 的那个。

<td class="read" colspan="4">
    <a href="#" id="button-read" onclick="formRead(); return false;" title="Read record from database" tabindex="1" class="button button-read">Read</a>
    <a id="button-new" title="Read new record from database" class="button button-new">New</a>
</td>

我尝试过使用:

new_button = driver.find_element_by_id("button-new")
new_button = driver.find_element_by_css_selector("A.button.button-new")
new_button = driver.find_element_by_xpath('//*[@id="button-new"]')

紧随其后

new_button.click()

但是我得到 NoSuchElementException 并且它无法找到它。

我在任何其他元素上都没有遇到过这个问题,也不知道哪里出错了。

编辑解决方案:

我意识到我需要切换 iframe

driver.switch_to.frame(driver.find_element_by_id("nested1"))

【问题讨论】:

  • 试试driver.find_element_by_id('button-read')
  • @bhupathituraga 这也没有找到,并且有两个按钮彼此相邻:读取和新建,我需要单击新建,所以我认为即使它找到了按钮读取它也不会帮助了我
  • 请保留更多html或分享按钮url
  • 请调试检查,点击之前网页已加载。否则,您需要将它与显式等待一起使用。
  • driver.find_element_by_class_name("button.button-new")

标签: python selenium button selenium-chromedriver


【解决方案1】:

要确定元素是否被定位,试试这个:

new_button_list = driver.find_elements_by_xpath('//a[@id="button-new"]')

由于使用了“元素”,这将返回一个列表:

然后检查列表的长度,一件好事是它不会通过异常并且让你知道元素是否被定位。

【讨论】:

  • 它根本找不到它(使用这种方式,列表长度 = 0),没有它我无法继续进行自动化测试的下一步
  • hmm,这个网页内容可以远程访问吗,我可以试试
  • 我可以说的一点是 xpath 没有任何问题,所以如果按钮在 dom 中,我不明白为什么会出现位置问题
【解决方案2】:

尝试将它与if 声明一起使用,也许他们专门放了一个空按钮来迷惑我们,

new_button = driver.find_element_by_id("button-new")
if new_button:
    new_button.click()

你能问find_elements_by_id有多少个btn吗?

btns = driver.find_elements_by_id("button-new")
print(btns)

# also we can check with # find_elements_by_id

btns = driver.find_elements_by_id("button-new")
if len(btns):
    new_button[0].click()

【讨论】:

  • 这意味着 if 语句没有被执行,因为没有 'new_button'。我也尝试将它们作为列表获取,长度为 0,因为没有找到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2021-06-21
  • 1970-01-01
相关资源
最近更新 更多