【问题标题】:AttributeError: "str' object has no attribute 'textAttributeError:“str”对象没有属性“文本”
【发布时间】:2018-01-15 08:30:57
【问题描述】:

我为 shopify 购物车制作脚本,因为无法手动购买,当我将脚本运行到命令提示符时, 它说,

第 109 行,在 AttributeError 中:“str' 对象没有属性 '文字

根据所选颜色抓取产品信息

        if blue and cinder:
            productInfo(urlBlueResponse.text)
            productInfo(urlCinderResponse.text)
        elif blue:
            productInfo(urlBlueResponse.text)
        elif cinder:
            productInfo(urlCinderResponse.text)
        else:
            print(Fore.RED + timestamp

有人告诉我这是由于大小写不匹配,有人可以向我解释一下吗?我是编码新手,我想尽我所能学习。

【问题讨论】:

  • 我们需要更多上下文(重现问题所必需的“完整”代码、您要执行的操作等)。另外,鉴于您发布的代码 sn-p,我不知道哪一行是 109。
  • 它不允许我发布整个脚本第 109 行是 productInfo(urlBlueResponse.text),
  • 我正在尝试通过命令脚本购买商品,以便它可以在售罄之前添加到购物车并在 chrome 中打开。通常商品会在一分钟内售罄。

标签: python attributes command


【解决方案1】:

当您尝试访问字符串对象上的属性时发生此错误 -- .text -- 该属性不作为该对象上的元素存在。

您的代码似乎正在处理某种 HTTP 请求和响应对象:urlBlueResponse

您在请求/响应周期中遇到错误或其他一些意外行为,导致其中一个响应对象返回str(字符串)类型而不是具有文本属性的响应对象,这似乎是合理的。我建议您使用 try/except 块处理异常:

try:    
    if blue and cinder:
        productInfo(urlBlueResponse.text)
        productInfo(urlCinderResponse.text)
    elif blue:
        productInfo(urlBlueResponse.text)
    elif cinder:
        productInfo(urlCinderResponse.text)
    else:
        print(Fore.RED + timestamp)
except AttributeError as e:
    #exception handler logic goes here
    print("got exception: ")
    print(e)
    #if error indicates your request is recoverable then do so:
    if recoverable(e):
        do_request(again)
    #if error is unrecoverable, decorate it and reraise it
    #(See *Link)
    # or just reraise it:
        raise(e)   

*链接:(Re-raise exception with a different type and message, preserving existing information)

【讨论】:

  • 异常处理逻辑是什么?抱歉,我明白你的意思,但我是个编程菜鸟。
  • @ortegabx05 编辑回答您关于异常处理的问题
【解决方案2】:

根据错误消息,urlBlueResponseurlCinderResponse(或两者)都是字符串数据类型。按照您使用它们的方式,您似乎希望它们是具有text 属性的对象。错误消息告诉您它们是 str 对象并且没有 text 属性。

【讨论】:

  • 所以基本上它告诉我网站中不存在该项目?
  • 如果可以的话,我会 -1 你 - 你只是在重申错误所说的内容。
  • 那是因为错误信息回答了他的问题。
  • @ortegabx05 它告诉您您使用了错误的数据类型。如果您包含较大部分的代码,其中创建了 urlBlueResponseurlCinderResponse,我们或许能够查明错误的根源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2021-10-04
  • 2019-12-02
  • 2021-09-25
  • 2014-03-04
  • 2013-09-22
相关资源
最近更新 更多