1

I made a program to open web pages using python 3.5 by using socket library. first, i prompt user to enter URL and then I split() that URL to extract host name for connect() method. But I am getting the following error which points towards my get request command:

cmd ='GET ' + user_url + ' HTTP/1.0\n\n'.encode() TypeError: Can't convert 'bytes' object to str implicitly

Following is my code:

import socket

user_url = input("Enter url: ")
host_name = user_url.split("/")[2]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((host_name, 80))
cmd ='GET ' + user_url + ' HTTP/1.0\n\n'.encode()
mysock.send(cmd)

while True:
   data = mysock.recv(512)
   if (len(data) < 1):
      break
   print (data.decode(),end='')

mysock.close()
2
  • 1
    haha: cmd =('GET ' + user_url + ' HTTP/1.0\n\n').encode() Commented Jul 18, 2018 at 15:55
  • (cmd ='GET ' + user_url + ' HTTP/1.0\n\n').encode()? Commented Jul 18, 2018 at 15:55

1 Answer 1

2
cmd ='GET ' + user_url + ' HTTP/1.0\n\n'.encode()
       ^         ^                ^
      str       str          bytes

this line encodes just the last part, and mixing string type with bytes type isn't possible, which explains the error.

You want to encode the whole string for instance like this:

cmd = ('GET ' + user_url + ' HTTP/1.0\n\n').encode()

Better yet, use format to avoid confusion and string addition:

cmd ='GET {} HTTP/1.0\n\n'.format(user_url).encode()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.