Selenium-find_elements命令,在哪里查看?

时间:2018-12-26 19:29:15

标签: python selenium

我正在研究一本Selenium with Python书籍,并对下面的这个特定示例感到困惑。以下测试运行正常:

import unittest
from ddt import ddt, data, unpack
from selenium import webdriver

@ddt
class SearchDDT(unittest.TestCase):
    def setUp(self):
        # create a new Chrome session
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

        # navigate to application home page
        self.driver.get('http://demo-store.seleniumacademy.com/')


    # specify test data using @ data decorator
    @data(("phones", 3), ("music", 5))
    @unpack
    def test_search(self, search_value, expected_count):
        # get the search textbox
        self.search_field = self.driver.find_element_by_name("q")
        self.search_field.clear()

        # enter serach keyword and submit
        # use search value argument to pass data
        self.search_field.send_keys(search_value)
        self.search_field.submit()

        # get all the anchor elements which have product names displayed current on result page
        products = self.driver.find_elements_by_xpath("//h2[@class='product-name']/a")

        # check count of products show in results
        self.assertEqual(expected_count, len(products))

    def tearDown(self):
        self.driver.quit()

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

尽管在此特定行上我感到困惑:

# get all the anchor elements which have product names displayed current on result page
        products = self.driver.find_elements_by_xpath("//h2[@class='product-name']/a")

正在检查哪些元素在页面的确切位置?有问题的测试页的快捷方式在这里:

http://demo-store.seleniumacademy.com/catalogsearch/result/?q=music

您可以看到返回了5个项目。我的问题是,该页面上上面显示的xpath覆盖5个项目,并且又使测试通过了?我尝试检查单个音乐项目本身,这是不正确的。基本上,我应该在哪里单击以检索“ find_elements_by_xpath”值?

1 个答案:

答案 0 :(得分:1)

所以他们以我的方式看待xpath基本上是在页面上查找元素的快捷方式,它是非常有用的元素。因此,为了找到某个元素的xpath,您将转到浏览器上的控制台。按F12或右键单击并单击检查或crtl + shift + i

然后在左上角看到一个光标,单击它,然后选择要在页面上找到的元素。在元素控制台上,选中的选择元素将突出显示。右键单击,您将看到复制xpath。这将直接带您到xpath元素。

或者根据您的情况给您//h2[@class='product-name']/a,因此crtl +f查找并粘贴xpath,它将显示弹出窗口的位置。