当我向服务器"www.python.org“发出请求时,我似乎得到了一个类型错误。我刚刚开始学习网络,我正在复习基础知识。我理解为什么类型错误本身会发生,因为字符串不是预期的,但根据我正在阅读的PDF教程,这是向服务器发出请求的格式,我输入错了吗??如何避免类型错误?谢谢。代码如下:
from socket import *
s = socket(AF_INET,SOCK_STREAM)
s.connect(("www.python.org",80)) # connect
s.send("GET /index.html HTTP/1.0\n\n") # send request
data = s.recv(10000) # get response
s.close()
发布于 2018-07-04 05:51:00
看起来你正在使用Python3。在Python3中,字符串文字是unicode对象。Unicode对象不能通过网络套接字发送,只能发送字节。
您正在阅读的教程可能是为Python 2编写的,其中字符串文字是字节而不是unicode。
在Python 2中:
this_is_bytes = "my string"
this_is_unicode = u"my string"
在Python 3中,默认情况下改变为使用unicode字符串:
this_is_bytes = b"my string"
this_is_unicode = "my string"
您需要将unicode字符串编码为字节:
s.send("GET /index.html HTTP/1.0\n\n".encode('ascii')) # send request
或使用字节字面量:
s.send(b"GET /index.html HTTP/1.0\n\n") # send request
https://stackoverflow.com/questions/51163173
复制相似问题