【发布时间】:2017-08-31 11:04:18
【问题描述】:
我正在使用以下脚本向谷歌发出请求。但是,当我执行它时,我收到错误说明:
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n") TypeError:需要一个类似字节的对象,而不是'str'
在 stackoverflow 中浏览类似问题时,建议将 client.sendto 与编码消息一起使用。但是,就我而言,没有传递任何消息。
以下是我使用的脚本:
import socket
target_host = "www.google.com"
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
response = client.recv(4096)
print(response)
任何有关纠正问题的指示将不胜感激。
【问题讨论】:
-
“没有消息”是什么意思?您显然是在发送 HTTP 请求。
-
在 Python 3 中,
""GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"是一个 unicode 字符串,.send()希望字节通过网络发送。您的代码尝试直接发送 unicode 字符串而不进行编码,错误消息理所当然地抱怨了这一点。
标签: python python-3.x