【问题标题】:Traceback when trying to read data from web pages尝试从网页读取数据时的回溯
【发布时间】:2017-08-26 21:35:55
【问题描述】:
# -*- 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
TypeError: 必须是 str,而不是 builtin_function_or_method

【问题讨论】:

    标签: python sockets network-programming


    【解决方案1】:

    你必须为字符串实例cmd调用方法encode()

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

    【讨论】:

    • @PavanVallapureddy 很高兴为您提供帮助!请考虑接受这个答案。谢谢!
    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多