从URL中提取查询字符串

2024-10-01 19:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从用户输入的url中提取查询字符串,该url将被转换为一个整数,所以http://127.0.0.1:8000/?1653。当我尝试这样做时,python给了我一个错误

File "C:\Users...\Documents\webserver\server.py", line 26, in do_GET int(URIextra) ValueError: invalid literal for int() with base 10: ''

我不知道我做错了什么,任何帮助都将不胜感激

import http.server, socketserver, os
from urllib.parse import urlparse
from shutil import copyfile

dirs = []

PORT = 8000

URIextra = ""


class CustomHandler(http.server.SimpleHTTPRequestHandler):

    def __init__(self, req, client_addr, server):
        http.server.SimpleHTTPRequestHandler.__init__(self, req, client_addr, server)

    def do_GET(self):
        o = urlparse(self.path)
        URIextra = str(o[4])
        http.server.SimpleHTTPRequestHandler.do_GET(self)
        print(URIextra)
        dirs = os.listdir()
        f = open("index.txt", "w")
        f.write(os.listdir())
        f.close()
        int(URIextra)
        copyfile(dirs[URIextra], "CurrentFile.mp3")

class MyTCPServer(socketserver.ThreadingTCPServer):
    allow_reuse_address = True

os.chdir(os.getcwd() + "/web")

httpd = MyTCPServer(('localhost', PORT), CustomHandler)
httpd.allow_reuse_address = True
print("Serving at port", PORT)
httpd.serve_forever()

Tags: importselfhttpurlgetserverosport
2条回答

您正在将URIExtra用作字符串:

URIextra = str(o[4])

你应该用这个:

URIextra = int(o[4])

我能够改变我的代码,以更有效地工作,没有我的电脑与我现在,将张贴在这里一点

相关问题 更多 >

    热门问题