【问题标题】:AttributeError: 'str' object has no attribute 'text':AttributeError:“str”对象没有属性“text”:
【发布时间】:2019-07-18 15:25:57
【问题描述】:

我正在尝试编写一个查看列表中所有值并确认列表中的值与预期值匹配的方法。我的 if 语句中出现 AttributeError。

@step('Confirm sources in the dropdown when uploading a file "{source_list}"')
def step_impl(context, source_list):

 open_list = context.browser.find_element_by_xpath("//select[@id='id_source']")
    if not open_list:
        raise ValueError('Source dropdown menu not found')
    open_list.click()
    time.sleep(3)
    source_options = context.browser.find_elements_by_xpath(
        "// *[ @ id = 'id_source']/option")
    for v in source_options:
        source = (v.get_attribute('innerHTML'))
        if source_list in source[0].text:
            print("Verified sources are in source list: ", source_list, "\n")
        else:
            raise ValueError("Source type of '%s' was not found in list" % source_list

我的功能文件中有一个示例,其中包含列表中的所有值。当我现在运行它时,我得到了

"AttributeError: 'str' 对象没有属性 'text':

【问题讨论】:

  • 您是否尝试在 source_options 中打印结果?无论如何,如果 source_list 是 if 语句中的列表,你应该做相反的事情,如果 source_list 在列表中而不是相反
  • source = (v.get_attribute('innerHTML')) 这会将innerHTML 作为字符串存储在source 中,当您尝试source[0].text 时,脚本会在您尝试.text 方法时抛出错误。你应该试试if source_list in source:。我觉得你应该用 xpath 做这个检查,而不是做一个循环。
  • 我一开始尝试了这个,我的 raise ValueError 被触发,即使该值在示例中并且也在 xpath 中。在这一行之后..... source = (v.get_attribute('innerHTML')) 我会添加 print(source)... 并打印预期值
  • 你的source_list是字符串还是列表你能确认一下

标签: python selenium automation


【解决方案1】:

这是带有 xpath 的简化版本。

@step('Confirm sources in the dropdown when uploading a file "{source_list}"')
def step_impl(context, source_list):

    open_list = context.browser.find_element_by_xpath("//select[@id='id_source']")
    if not open_list:
        raise ValueError('Source dropdown menu not found')
        if open_list.find_element_by_xpath("./option[contains(text(),'" + source_list + "')]"):
            print("Verified sources are in source list: ", source_list, "\n")
        else:
            raise ValueError("Source type of '%s' was not found in list" % source_list

【讨论】:

    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2021-10-04
    • 2019-12-02
    • 2021-09-25
    相关资源
    最近更新 更多