简体   繁体   English

尝试从网页读取数据时的回溯

[英]Traceback when trying to read data from web pages

# -*- 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()

Enter url: http://data.pr4e.org/romeo.txt 输入网址: http : //data.pr4e.org/romeo.txt
Enter port: 80 输入端口:80
Traceback (most recent call last): 追溯(最近一次通话):
File "exercise1.py", line 17, in 在第17行的文件“ exercise1.py”
cmd = "GET " + url + " HTTP/1.0\\r\\n\\r\\n".encode cmd =“ GET” + url +“ HTTP / 1.0 \\ r \\ n \\ r \\ n” .encode
TypeError: must be str, not builtin_function_or_method TypeError:必须为str,而不是buildin_function_or_method

You have to call the method encode() for string instance cmd : 您必须为字符串实例cmd调用方法encode()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM