【问题标题】:Python selenium unable to find element neither by class name nor xpathPython selenium 无法通过类名和 xpath 找到元素
【发布时间】:2017-03-20 16:58:14
【问题描述】:

我是 Selenium 的新手。我开始通过书本学习 Selenium。而且我与 Selenium 的不明确行为作斗争。出于教育目的,我使用这个网站: http://magento-demo.lexiconn.com/ - 我正在尝试通过类名(即:class='button search button')或通过 xpath 查找搜索按钮

search_button = self.driver.find_element_by_xpath('/html/body/div/div[2]/header/div/div[4]/form/div[1]/button')

search_button = self.driver.find_element_by_class_name('button')

但每次 selenium 都找不到它。请帮助我理解这种行为的原因。谢谢你

我使用了 Selenium IDE,它显示 XPATH: //button[@type='submit']

当我尝试通过 xpath 查找元素时,我遇到了同样的错误,这很奇怪。请指教。

我的代码是:

import unittest
from selenium import webdriver

class HomePageTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        #create new Firefox session
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(30)
        cls.driver.maximize_window()

        #navvigate to application home page
        cls.driver.get('http://magento-demo.lexiconn.com/')

    def test_search__text_field_max_length(self):
        #get the search text box
        search_field=self.driver.find_element_by_id("search")

        #check maxlenght attribute st to 128
        self.assertEqual("128",search_field.get_attribute("maxlength"))

    def test_search_button_enabled(self):
        # get Search button
        search_button = self.driver.find_element_by_class_name('button')

        # check Search button is enabled
        self.assertTrue(search_button.is_enabled())



    @classmethod
    def tearDown(self):
        #close the browser window
        self.driver.quit()


if __name__=='__main__':
    unittest.main(verbosity=2)

【问题讨论】:

  • 请包含您收到的任何错误消息。

标签: python selenium-webdriver


【解决方案1】:

试试这个:

search_button = self.driver.find_element_by_xpath('//button[@class="button search-button"]')

【讨论】:

  • TearDown 方法出错。我想做出更大的答案,但我被禁止了。 :'-( 如果论坛有教育部分?
【解决方案2】:

尝试下载 selenium IDE 插件,安装并开始录制。单击所需的按钮并查看其目标在 IDE 中的记录方式。以编程方式,selenium 将接受与 IDE 相同的 xpath 和其他选择器。在 IDE 中记录后,目标字段上有一个下拉菜单,可让您查看选择该元素的所有不同方式,即 xpath 与按类等。

http://www.seleniumhq.org/projects/ide/

你可以试试:

css=button.button.search-button
//button[@type='submit']
//form[@id='search_mini_form']/div/button

【讨论】:

    【解决方案3】:

    我认为问题在于您的定位器不够具体。页面上有多个button,页面上有多个class=button的元素。这个 CSS 选择器对我有用。

    self.driver.find_element_by_css_selector("button[title='Search']")
    

    【讨论】:

      【解决方案4】:

      xpath locator试试这个方法

      说明:使用title标签的title属性。

      self.driver.find_element_by_xpath("//button[@title='Search']")
      

      说明:使用<button>标签的titletype属性。

      self.driver.find_element_by_xpath("//button[@title='Search'][@type='submit']")
      

      【讨论】:

      • 如果解决了您的问题,请将此答案标记为Accepted
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      相关资源
      最近更新 更多