mbvee
mbvee

Reputation: 391

Python TypeError: a bytes-like object is required, not 'str'

I am using the below script to make request to google. However, when I execute it, I get the error stating:

client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n") TypeError: a bytes-like object is required, not 'str'

On browsing for similar issues in stackoverflow, client.sendto has been recommended to use along with encoding the message. However, in my case there is no message that is passed.

The below is the script I use:

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)

Any pointers on correcting the issue will be appreciated.

Upvotes: 3

Views: 10505

Answers (1)

Luca Citi
Luca Citi

Reputation: 1420

You need to choose an encoding, example:

client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n".encode(encoding='utf-8'))

See also: Python Socket Send Buffer Vs. Str and TypeError: 'str' does not support the buffer interface

Upvotes: 6

Related Questions