猿问

类型错误:“float”和“bytes”实例之间不支持“>=”

谁能帮我解决我的这个问题?这是我的代码:


import RPi.GPIO as GPIO 

import time

import Adafruit_DHT

import urllib.request


GPIO.setmode (GPIO.BCM)

GPIO.setwarnings(False)


GPIO.setup (13, GPIO.OUT)

GPIO.output(13, 1)



def getSensorData(): 

   humidity, temp = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 22) 

   return (float(humidity), float(temp))


baseURL = 'https://mekatronika15.000webhostapp.com/data.php?api_key=%s'

inputURL= 'https://mekatronika15.000webhostapp.com/admin/tes2.php'

try:


   while True:

      humidity, temp = getSensorData()

      humidity = '%.2f' % humidity

      temp = '%.2f' % temp


      try:

         conn = urllib.request.urlopen(baseURL + "&humidity=%s&temp=%s" % (humidity, temp))

         conn1 = urllib.request.urlopen(inputURL)

         print (conn.read())

         conn.close()

         status1 = conn1.read()

         sleep(20)

      except: 

         print ('exiting.')

        

         print (humidity, temp)


    

      if float(temp) >= status1:

         GPIO.output(13, 0)

            

      elif float(temp) <= status1:

         GPIO.output(13, 1)    

         


except KeyboardInterrupt:

    GPIO.cleanup()

以及它给出的错误:


if float(temp) >= (status1):

TypeError: '>=' not supported between instances of 'float' and 'bytes'

不幸的是,我对 python 不熟悉,所以我被困住了,我知道这个应用程序中有很多类似的问题和答案,我已经尝试了一些,但仍然收到错误。


胡说叔叔
浏览 135回答 3
3回答

BIG阳

由于在使用变量之前不需要声明它,因此在尝试对变量进行操作时需要格外小心。问题是这一行status1 = conn1.read()&nbsp;Here,conn1.read()返回网页的内容,即源html作为字节序列(类似于字符串)。将数字与字符序列进行比较是未定义的操作;因此,python 引发了一个错误。您可以设计一个解析器来检索您需要的信息。例如,您可以使用将拥有的字节转换为字符串encode()。然后是你想要find()的索引status1。然后您可以使用 substring 获取status1字符串,最后将其转换为数字。

拉莫斯之舞

status1以字节形式返回,需要格式化。在睡眠之前打印(status1)或使用调试器检查该值。我的猜测是,您需要对收到的回复进行更多分析。该库requests是 urllib 的包装器,通常更有用,因此您不需要所有这些步骤。&nbsp;&nbsp;&nbsp;&nbsp;response&nbsp;=&nbsp;requests.get(url) &nbsp;&nbsp;&nbsp;&nbsp;response.json&nbsp;&nbsp;#&nbsp;probably&nbsp;has&nbsp;what&nbsp;you&nbsp;need

慕后森

该urllib.request.urlopen()函数返回一个HTTPResponse对象:import urllib.requestconnection = urllib.request.urlopen("https://stackoverflow.com/")type(connection) # <class 'http.client.HTTPResponse'>read对象的方法( HTTPConnection您使用语句调用status1 = conn1.read())在文档中描述如下:读取并返回响应正文,或直到下一个 amt bytes。(强调我的)因此,您收到类型错误的原因是HTTPConnection.readreturn bytes,它无法与float. 您需要将 转换bytes为float. 如果conn1.read()只是以字节形式返回一个数字,您可以使用float(status1),但我高度怀疑status1其格式有点复杂,因此您需要进行一些挖掘以弄清楚您到底想要从中提取数据的内容和方式它。您可能需要研究像BeautifulSoup这样的 HTML 解析器来帮助您提取您要查找的数据。
随时随地看视频慕课网APP

相关分类

Python
我要回答