.find() 不带字符串? Python 3.6
.find() does not take a string? Python 3.6
我最近一直在从事一个项目,该项目从 NOAA 网站检索 METAR,并将 METAR 数据切片并打印出来。现在我遇到了一个问题,因为将代码更改为 Python3.6
,当我尝试 .find()
表示 METAR 数据开始的标记时,它给我这个错误消息:
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)
根据 the documentation, it takes a bytes-like object or an int.
这里有两种类型:str
和bytes
。两者都有一个 .find
方法。很容易误会他们。您的 website_html
文件实际上是 bytes
,而不是 str
。
HTTPResponce.read()
returns 一个 bytes
对象。 bytes
方法(例如 .find
)需要 bytes
类型的参数。
您可以将 br1_string
更改为 bytes
对象:
br1_string = b"<!-- Data starts here -->"
或者,解码响应:
website_html = website.read().decode()
我最近一直在从事一个项目,该项目从 NOAA 网站检索 METAR,并将 METAR 数据切片并打印出来。现在我遇到了一个问题,因为将代码更改为 Python3.6
,当我尝试 .find()
表示 METAR 数据开始的标记时,它给我这个错误消息:
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)
根据 the documentation, it takes a bytes-like object or an int.
这里有两种类型:str
和bytes
。两者都有一个 .find
方法。很容易误会他们。您的 website_html
文件实际上是 bytes
,而不是 str
。
HTTPResponce.read()
returns 一个 bytes
对象。 bytes
方法(例如 .find
)需要 bytes
类型的参数。
您可以将 br1_string
更改为 bytes
对象:
br1_string = b"<!-- Data starts here -->"
或者,解码响应:
website_html = website.read().decode()