【问题标题】:Difficulty finding elements in Selenium with Python使用 Python 在 Selenium 中难以找到元素
【发布时间】:2018-05-25 23:21:23
【问题描述】:

我正在尝试熟悉 Selenium,但在寻找元素时遇到了问题,实际上我注意到了很多。

我想去 yahoo.com,点击 Sports,然后断言页面标题是正确的。以下引发“无法定位元素”错误消息。我尝试过 ID、xPath 等。我还尝试过其他页面元素、邮件、新闻等……都抛出相同的错误。我在这里遗漏了什么吗?

import unittest
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# go to Yahoo home page, click on Sports and assert title is correct

class searchMaps(unittest.TestCase):
    # def setup as class method
    @classmethod
    def setUpClass(inst):
        inst.driver = webdriver.Chrome()
        inst.driver.maximize_window()
        inst.driver.get("http://www.yahoo.com")
        inst.driver.implicitly_wait(20)

    def test_click_sports_page(self):
        self.search_field = self.driver.find_element_by_id('yui_3_18_0_3_1527260025921_1028')
        self.search_field.click()
        actual_title = driver.getTitle()
        expected_title = 'Yahoo Sports | Sports News'
        assertEquals(actual_title, expected_title)


    @classmethod
    def tearDownClass(inst):
        inst.driver.quit()


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

【问题讨论】:

  • 这个 id yui_3_18_0_3_1527260025921_1028 不是动态的,应该在下次运行时改变吗?

标签: python selenium


【解决方案1】:

目标链接的@id是动态的,所以每次打开页面都会不同。

尝试使用链接文本来定位元素:

self.search_field = self.driver.find_element_by_link_text('Sports')

【讨论】:

  • 感谢您的帮助。这确实让我克服了那个错误,但现在我看到了 NameError: name 'driver' is not defined 与以下相关:actual_title = driver.getTitle()
  • 试试actual_title = self.driver.title
  • 啊,谢谢。我现在看到其他错误,但你解决了我最初的问题。生病通过其他工作。感谢您的帮助
猜你喜欢
  • 2019-03-07
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 2022-01-27
相关资源
最近更新 更多