.find()不带字符串? Python 3.6
问题描述:
我最近一直在研究一个项目,它从NOAA网站获取METAR,并切割METAR数据并打印它。现在我遇到了问题,更改代码以Python3.6
,当我尝试.find()
那心满意足的METAR数据的开始它给我这个错误消息的标记:.find()不带字符串? Python 3.6
File "/Users/MrZeus/Desktop/PY3.6_PROJECT/version_1.py", line 22, in daMainProgram
data_start = website_html.find("<--DATA_START-->")
TypeError: a bytes-like object is required, not 'str'
我明白这是什么错误说法。这意味着.find()
不接受字符串,但根据python文档.find()
函数确实需要一个字符串!
这里是我遇到的麻烦的一段代码:
website = urllib.request.urlopen(airid)
website_html = website.read()
print(website_html)
br1_string = "<!-- Data starts here -->"
data_start = website_html.find(br1_string)
br1 = data_start + 25
br2 = website_html.find("<br />")
metar_slice = website_html[br1:br2]
print("Here is the undecoded METAR data:\n"+metar_slice)
答
HTTPResponce.read()
返回一个bytes
对象。 bytes
方法(如.find
)需要参数类型bytes
。
你可以要么改变br1_string
为bytes
对象:
br1_string = b"<!-- Data starts here -->"
或解码响应:
website_html = website.read().decode()
答
按the documentation, it takes a bytes-like object or an int。
这里有两种类型:str
和bytes
。两者都有一个.find
方法。很容易让他们误会。您的website_html
文件实际上是bytes
,而不是str
。
谢谢sooooooo多! –