2017-08-26 51 views
1
# -*- coding: utf-8 -*- 
""" 
Created on Sat Aug 26 17:31:06 2017 

@author: Pavan Vallapureddy 
""" 
""" 
Write a program to prompt the user for the URL so it can read any web page. 
You can use split('/') to break the URL into its component parts so you can 
extract the host name for the socket connect call. 
""" 

import socket 

url = input("Enter url: ") 
port = int(input("Enter port: ")) 
urlSplit = url.split("/") 
host = urlSplit[2] 

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
mysock.connect((host, port)) 
cmd = "GET " + url + " HTTP/1.0\r\n\r\n".encode 
mysock.send(cmd) 

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

輸入網址:http://data.pr4e.org/romeo.txt
輸入端口:80
回溯(最近通話最後一個):
文件 「exercise1.py」 17行,在
CMD = 「GET」 + URL + 「HTTP/1.0 \ r \ n \ r \ n」 個.encode
類型錯誤:必須海峽,不builtin_function_or_method回溯試圖從網頁讀取數據時

回答

0

你要調用的方法encode()的字符串實例cmd

cmd = "GET " + url + " HTTP/1.0\r\n\r\n" 
mysock.send(cmd.encode()) 
+0

工作。感謝您的幫助 –

+0

@PavanVallapureddy很高興幫助!請考慮接受這個答案。謝謝! – Ajax1234