Python3.3 HTML客户端类型错误:“str”不支持

2024-05-19 08:59:03 发布

您现在位置:Python中文网/ 问答频道 /正文

import socket

# Set up a TCP/IP socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# Connect as client to a selected server
# on a specified port
s.connect(("www.wellho.net",80))

# Protocol exchange - sends and receives
s.send("GET /robots.txt HTTP/1.0\n\n")
while True:
        resp = s.recv(1024)
        if resp == "": break
        print(resp,)

# Close the connection when completed
s.close()
print("\ndone")

错误:

cg0546wq@smaug:~/Desktop/440$ python3 HTTPclient.py
Traceback (most recent call last):
  File "HTTPclient.py", line 11, in <module>
    s.send("GET /robots.txt HTTP/1.0\n\n")
TypeError: 'str' does not support the buffer interface

不能使用

  • urllib.request.urlopen
  • urllib2.urlopen
  • http
  • http.client
  • httplib

Tags: thepyimporttxtclientsendhttpget
2条回答
import socket

# Set up a TCP/IP socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# Connect as client to a selected server
# on a specified port
s.connect(("www.google.com",80))

# Protocol exchange - sends and receives
s.send(b"GET /index.html HTTP/1.0\n\n")
while True:
        resp = s.recv(1024)
        if resp == b'': break
        print(resp,)

# Close the connection when completed
s.close()
print("\ndone")

Sockets只能接受字节,而您尝试将Unicode字符串发送给它。

将字符串编码为字节:

s.send("GET /robots.txt HTTP/1.0\n\n".encode('ascii'))

或者给它一个字节文本(以b前缀开头的字符串文本):

s.send(b"GET /robots.txt HTTP/1.0\n\n")

考虑到接收的数据也将是bytes值;您不能只将这些值与''进行比较。只需测试空的响应,您可能希望在打印时解码对str的响应:

while True:
    resp = s.recv(1024)
    if not resp: break
    print(resp.decode('ascii'))

相关问题 更多 >

    热门问题