首页 > 解决方案 > 如何在 selenium python 中获取 h2 标签内的文本

问题描述

如何获取 html 标记内的文本并断言它是否存在于页面上。

html-

<h2>  You are suggested the Low Fat Vegan Diet </h2>

我试过了-

message = driver.find_elements_by_tag_name('h2').Text()

AttributeError:“列表”对象没有属性“文本”

 message = driver.find_elements_by_tag_name('h2').getText()

AttributeError:“列表”对象没有属性“getText”

我如何获取文本并断言它存在于页面中?

标签: pythonseleniumselenium-webdriverselenium-chromedriverassertion

解决方案


方法名称是 find_elements_by_tag_name这样它返回一个列表elements。如果您的目标元素是元素中的第一项,您可以试试这个:

message = driver.find_elements_by_tag_name('h2')[0].text

我建议您使用Beautifulsoup来更好地搜索元素。


推荐阅读