1. Home
  2. Computing & Technology
  3. Python

Building a Web Client in Python

From Al Lukaszewski, for About.com

9 of 9

The Python Code for a Simple Web Client Program

To ensure that you have all the lines needed for this program, here is the code for this web client.

#!/usr/bin/env python

# import sys for handling command line argument
# import socket for network communications
import sys, socket

# hard-wire the port number for safety's sake
# then take the names of the host and file from the command line
port = 80
host = sys.argv[1]
filename = sys.argv[2]

# create a socket object called 'c'
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect to the socket
c.connect((host, port))

# create a file-like object to read
fileobj = c.makefile('r', 0)

# Ask the server for the file
fileobj.write("GET "+filename+" HTTP/1.0\n\n")

# read the lines of the file object into a buffer, buff
buff = fileobj.readlines()

# step through the buffer, printing each line
for line in buff:
     print line

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Networking
  5. Programming A Simple Web Client in Python : the Python Code for a Simple Web Client Program

©2009 About.com, a part of The New York Times Company.

All rights reserved.