如何在硒中获得“ nth-of-type”

时间:2018-07-20 19:30:13

标签: python selenium automated-tests

我正在使用Selenium Webdriver检查该特定段落的文本(此处以蓝色突出显示):

enter image description here

但是如何“查询”该段落?

这是我正在尝试的(不起作用):

    def test_intro_text(self):
       """Test that intro text is expected text"""
       container = self.browser.find_element_by_id('visual-17')
       hed_dek_wrapper = container.find_element_by_class_name('hed-dek-wrapper')
       intro_text = hed_dek_wrapper.findElement('p:nth-of-type(2)')
       self.assertIn(
        'Over the past 20 years, we have seen an evolution.',
        intro_text.text
       )

我遇到此错误:AttributeError:'WebElement' object has no attribute 'findElement'

2 个答案:

答案 0 :(得分:2)

findElement()不是Python。请尝试以下操作:

intro_text = hed_dek_wrapper.find_element_by_css_selector('p:nth-of-type(2)')
assert 'Over the past 20 years, we have seen an evolution.' in intro_text.text

答案 1 :(得分:0)

只需使用此css选择器即可:

#visual-7 .hed-dek-wrapper >p:nth-of-type(2)  

并使用CSS选择器查找元素,它将为您提供第二个p标签。

driver.find_element_by_css_selector("#visual-7 .hed-dek-wrapper >p:nth-of-type(2)");